【问题标题】:Rails 4: checkboxes with a has_many throughRails 4:带有 has_many 的复选框
【发布时间】:2013-04-26 17:35:40
【问题描述】:

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

我已经建立了这些模型:

#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

现在我希望将表单保存到雇主分配表,但我用于表单的以下代码不起作用。

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

我确实将 :employer_ids 添加到了我的分配控制器中,我尝试从该控制器发送创建分配但未在employer_assignment 表中创建记录的表单。 当我通过控制台添加它们时( Assignment.last.employers

提前致谢。

【问题讨论】:

  • 您找到解决方案了吗?我有一个类似的问题。不保存到数据库
  • IIRC rails 4 默认使用强参数,不支持数组类型。因此,您需要明确定义 employer_ids 应该是一个数组,以便允许通过。

标签: has-many-through ruby-on-rails-4


【解决方案1】:

由于 rails4 中的强参数(@emil-kampp 提到了这一点),您的日志中可能会收到 Unpermitted parameters:,在生成新的 rails 后,它们会在您的控制器中生成。所以使用你的代码它看起来像:

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

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

另请参阅 SO 上的 Question 来回答这个问题。希望这可以为某人节省几个周期。

【讨论】:

    猜你喜欢
    • 2016-02-18
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2016-11-28
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多