2

我有三个表格,帐户、活动和帐户活动。我想在广告系列编辑表单中为选定帐户设置复选框。

我有这样的 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
4

1 回答 1

2

Ok, finally I got it, is not necessary to use has_many :through as many people recomends, this is the easiest setup possible i think to add checkboxes for select items on a HABTM (has and belongs to many, many has many) relationship.

To recapitulate I want to have checkboxes on campaig to select the accounts that campaign will use.

First, on the model for the form you want to add the checkboxes

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

Second, There's NO need to create the relationship on the other model (Account)

Third, On the form, this is haml, (this maybe could be optimized):

  = 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}"
于 2012-10-18T18:27:47.410 回答