如何在rails中编写强参数

时间:2017-02-20 11:28:03

标签: ruby ruby-on-rails-4

如何使用强参数实现以下创建操作

  def create
      #@user = User.find(params[:user_id])

       @listing = Listing.find(params[:listing_id])

       if current_user != @listing.user
                       @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price],
                                    total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate],
                                    driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'PENDING')
    else
        @reservation=Reservation.new(user_id:current_user.id,listing_id:params[:reservation][:listing_id],price:params[:reservation][:price],
                                    total:params[:reservation][:total],start_date:params[:reservation][:sdate],end_date:params[:reservation][:edate],
                                    driver_name:params[:reservation][:driver_name],no_of_passengers:params[:reservation][:no_of_passengers],days:params[:reservation][:days],reservation_status:false,reservation_state: 'BLOCKED')
    end
    @reservation.save
    end

我拥有来自_form.html.erb的所有属性,接受user_id,reservation_status和reservation_state.I可以允许一些属性:

def reservation_params  
    params.require(:reservation).permit(:start_date, :end_date, :price, :listing_id,:total,:driver_name,:no_of_passengers,:days)

如何允许用户完成预订的所有属性,包括user_id,reservation_status和reservation_state

提前致谢!

1 个答案:

答案 0 :(得分:2)

我会从这样的事情开始:

def reservation_params
  parameters = params.require(:reservation).permit(
    :listing_id, :sdate, :edate, :driver_name, :no_of_passengers, :days
  )

  parameters.merge!(user_id: current_user.id, reservation_status: false)

  if current_user != listing.user
    parameters.merge!(reservation_state: 'PENDING')
  else
    parameters.merge!(reservation_state: 'BLOCKED')
  end
end

def listing
  @listing ||= Listing.find(params[:listing_id])
end