如何使用带有has_many的Rails 4强参数:通过关联?

Lee*_*lly 34 activerecord many-to-many strong-parameters ruby-on-rails-4

我无法获得has_many:通过使用Rails 4强大参数的关联.我有一个名为的模型Checkout,我需要Employee在新的结帐表单中从模型中选择一个人.结账和员工通过Employment模型关联.

我尝试创建新的结帐时收到此错误:

NoMethodError in CheckoutsController#create
undefined method `employee' for #<Checkout:0x007ff4f8d07f88>
Run Code Online (Sandbox Code Playgroud)

似乎我的创建操作,结帐参数或我的新结帐表单都有问题.这是创建动作:

  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
Run Code Online (Sandbox Code Playgroud)

我的结帐参数:

def checkout_params
      params.require(:checkout).permit(:job, :employee_ids, :shift, :date, :hours, :sales, :tips, :owed, :collected, :notes)
end
Run Code Online (Sandbox Code Playgroud)

我的新结账表格:

<div class="field">
     <%= f.label :employee %><br>
     <%= f.collection_select(:employee_ids, Employee.all.collect, :id, :full_name, {:prompt => "Please select"} ) %>
</div>
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚Rails 4和强参数的变化.在Rails 3中,这种类型的关联和形式使用attr_accessible而不是strong_parameters为我工作.

相关文件

完整跟踪错误:https: //gist.github.com/leemcalilly/0cb9e2b539f9e1925a3d

models/checkout.rb: https: //gist.github.com/leemcalilly/012d6eae6b207beb147a

controllers/checkouts_controller.rb:https: //gist.github.com/leemcalilly/a47466504b7783b31773

views/checkouts/_form.html.erb https://gist.github.com/leemcalilly/ce0b4049b23e3d431f55

models/employee.rb: https: //gist.github.com/leemcalilly/46150bee3e6216fa29d1

controllers/employees_controller.rb:https: //gist.github.com/leemcalilly/04f3acdac0c9a678bca8

models/employment.rb: https: //gist.github.com/leemcalilly/6adad966dd48cb9d1b39

db/schema.rb: https://gist.github.com/leemcalilly/36be318c677bad75b211

小智 53

请记住,您为强参数(employees,employee_ids等)提供的名称在很大程度上是无关紧要的,因为它取决于选择提交的名称.基于命名约定,强参数不起作用.

https://gist.github.com/leemcalilly/a71981da605187d46d96在'employee_ids'上抛出"未经许可的参数"错误的原因是因为它需要一个标量值数组,按照https://github.com/rails/strong_parameters #nested-parameters,而不仅仅是标量值.

# If instead of:
... "employee_ids" => "1" ...
# You had:
... "employee_ids" => ["1"]
Run Code Online (Sandbox Code Playgroud)

然后您的强参数将起作用,具体来说:

... { :employee_ids => [] } ...
Run Code Online (Sandbox Code Playgroud)

因为它接收标量值数组而不是标量值.