简体   繁体   English

用表格中的参数来跟踪新对象

[英]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 = 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 nil:NilClass的未定义方法'id'

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 . 首先,您得到的错误是由于current_user变量为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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