Rails HABTM with checkboxes

。_饼干妹妹 提交于 2019-12-09 03:21:30

问题


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


来源:https://stackoverflow.com/questions/12960289/rails-habtm-with-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!