【发布时间】:2013-07-02 21:39:48
【问题描述】:
我在获取 has_many 时遇到了麻烦:通过关联使用 Rails 4 的强参数。我有一个名为 Checkout 的模型,我需要在新的结帐表单中从 Employee 模型中选择一个人。 Checkouts 和Employees 通过Employment 模型关联。
我在尝试创建新结帐时收到此错误:
NoMethodError in CheckoutsController#create
undefined method `employee' for #<Checkout:0x007ff4f8d07f88>
我的创建操作、结帐参数或新结帐表单似乎有问题。这是创建操作:
def create
@user = current_user
@checkout = @user.checkouts.build(checkout_params)
respond_to do |format|
if @checkout.save
format.html { redirect_to @checkout, notice: 'Checkout was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
我的结帐参数:
def checkout_params
params.require(:checkout).permit(:job, :employee_ids, :shift, :date, :hours, :sales, :tips, :owed, :collected, :notes)
end
我的新结帐表格:
<div class="field">
<%= f.label :employee %><br>
<%= f.collection_select(:employee_ids, Employee.all.collect, :id, :full_name, {:prompt => "Please select"} ) %>
</div>
但我无法弄清楚 Rails 4 和强大的参数发生了什么变化。在 Rails 3 中,这种类型的关联和表单使用 attr_accessible 而不是 strong_parameters 对我有用。
相关文件
错误的完整跟踪: https://gist.github.com/leemcalilly/0cb9e2b539f9e1925a3d
模型/checkout.rb: https://gist.github.com/leemcalilly/012d6eae6b207beb147a
控制器/checkouts_controller.rb: https://gist.github.com/leemcalilly/a47466504b7783b31773
views/checkouts/_form.html.erb https://gist.github.com/leemcalilly/ce0b4049b23e3d431f55
模型/employee.rb: https://gist.github.com/leemcalilly/46150bee3e6216fa29d1
控制器/employees_controller.rb: https://gist.github.com/leemcalilly/04f3acdac0c9a678bca8
模型/employment.rb: https://gist.github.com/leemcalilly/6adad966dd48cb9d1b39
db/schema.rb: https://gist.github.com/leemcalilly/36be318c677bad75b211
【问题讨论】:
-
遇到同样的问题。我认为问题在于,集合选择不只是提交员工 ID,而是将其包装在哈希中。在你的情况下“employee_ids”=>{“employee_id”=>“1”,“employee_id”=>“1”}。我敢打赌,如果你检查你的日志,会有一行写着“Unpermitted parameters:employee_ids”或类似的。
-
我认为这是正确的方向。这是我的开发日志:gist.github.com/leemcalilly/cc2a71bef9a1e14fc5e6 现在如何解决这个问题?
-
我将我的 checkout_params 更新为 gist.github.com/leemcalilly/a71981da605187d46d96,现在我得到了
Unpermitted parameters,如您在此处看到的:gist.github.com/leemcalilly/ef0a58695b7318f068ab
标签: activerecord many-to-many ruby-on-rails-4 strong-parameters