带复选框的Rails HABTM

我有三个表,帐户,广告系列和accounts_campaigns。 我希望在广告系列修改表单中为选定帐户设置复选框。

我有这样的Campaign模型:

class Campaign < ActiveRecord::Base has_and_belongs_to_many :accounts accepts_nested_attributes_for :accounts end 

我想我不需要在Account上定义关系。

我的表格是:

 = hidden_field_tag "campaign[accounts_ids][]", nil - Account.all.each do |account| %label.checkbox = check_box_tag "campaign[accounts_ids][]", account.id, @campaign.account_ids.include?(account.id), id: dom_id(account) = "#{account.name} - #{account.email}" 

但是我收到了这个错误:

 unknown attribute: accounts_ids 

好吧,最后我明白了,没有必要使用has_many:通过尽可能多的人推荐,这是最简单的设置,我认为可以为HABTM上的选择项添加复选框(已经并且属于很多很多很多)关系。

总结一下,我希望在Campaig上有复选框来选择广告系列将使用的帐户。

首先 ,在要添加复选框的表单模型上

 class Campaign < ActiveRecord::Base has_many :mail_sequences, order: 'step' has_and_belongs_to_many :accounts accepts_nested_attributes_for :accounts end 

第二 ,没有必要在另一个模型上建立关系(账户)

第三 ,在表单上,​​这是haml,(这可能是优化的):

  = hidden_field_tag "campaign[account_ids][]", nil - Account.all.each do |account| %label.checkbox = check_box_tag "campaign[account_ids][]", account.id, @campaign.account_ids.include?(account.id), id: dom_id(account) = "#{account.name} - #{account.email}"