Rails HABTM with checkboxes

2020-03-28 02:19发布

问题:

I have three tables, accounts, campaigns and accounts_campaigns. I want to have checkboxes for select accounts in the campaigns edit form.

I have Campaign's model like this:

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

I think i dont need to define the relationship on Account.

And my form is:

= 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}"

But i received this error:

unknown attribute: accounts_ids

回答1:

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}"