简体   繁体   中英

Rails new Object with Params from the Form

I have an model called Order and i want initiate with some params like below

@order = Order.new(user_id: current_user.id, type_of_order: 'events', order_date: DateTime.now)

i get the error

undefined method `id' for nil:NilClass

Is there an easy to to mass assign there parameters than having to do something like

@order[:order_date] = DateTime.now
@order[user_id] = current_user.id

First of all, the error you are getting is due to the fact that your current_user variable is nil . I guess you don't want to have an order without a user, so you should revise your code's logic to avoid that.

Second, if you want to be able to mass-assign parameters you have to specify in the controller creating or modifying the object which parameters can be assigned at once:

@order = Order.new(order_params)

...

private
def order_params
  params.require(:order).permit(:order_date, :user_id)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM