Rails 4:具有has_many的复选框 [英] Rails 4: checkboxes with a has_many through

查看:64
本文介绍了Rails 4:具有has_many的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个必须将任务分配给多个雇主的应用程序.

I'm building an application which has to assign a assignment to multiple employers.

我已经建立了以下模型:

I have build these models:

#assignment.rb
class Assignment < ActiveRecord::Base
    has_many :employer_assignments
    has_many :employers, :through => :employer_assignments
end

#employer.rb
class Employer < ActiveRecord::Base
    has_many :employer_assignments
    has_many :assignments, :through => :employer_assignments
end

#employer_assignment.rb
class EmployerAssignment < ActiveRecord::Base
    belongs_to :employer
    belongs_to :assignment
end

现在我希望将表单保存到owner_assignment表中,但是我在表单中使用的以下代码不起作用.

And now I want the form to save to the employer_assignment table but the following code I used for my form doesn't work.

<div class="field">
    <%= f.label :employer_ids %><br />
    <%= collection_check_boxes(:assignment, :employer_ids, Employer.all, :id, :name) %>
</div>

我确实将:employer_ids添加到我的工作分配控制器中,我尝试从该控制器发送表格,该表格的确创建了工作分配,但未在loyer_assignment表中创建记录. 当我通过控制台添加它们时(Assignment.last.employers<< Employer.all ),一切正常.我确定我遗漏了一些东西,但无法弄清楚是什么.

I did add :employer_ids to my assignment controller from which I try to send the form which does create the assignment but doesn't create the records in the employer_assignment table. When I add them via the console ( Assignment.last.employers << Employer.all ) it all works fine. I'm sure I'm missing something but can't figure out what.

谢谢.

推荐答案

由于新的rails生成后,由于rails4("@ emil-kampp"提到了此参数)中的强参数",您可能会在日志中得到Unpermitted parameters:.它们是在您的控制器中生成的.因此,使用您的代码看起来像:

You're probably getting an Unpermitted parameters: in your log due to Strong Parameters in rails4 (@emil-kampp mentioned this), after a fresh rails generate, they are generated in your controller. So using your code it would look something like:

class EmployersController < ApplicationController
  # <snip>
  def update
    @employer.update(employer_params)
  end

  def employer_params
    params.require(:employer).permit(:name, { :employer_ids => [] })
  end
end

也请参见问题可以回答这个问题.希望这可以节省一些人的时间.

Also see this Question on SO which answers this. Hopefully this saves someone a few cycles.

这篇关于Rails 4:具有has_many的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆