带复选框的 Rails HABTM [英] Rails HABTM with checkboxes

查看:42
本文介绍了带复选框的 Rails HABTM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个表,accounts、campaign 和 accounts_campaigns.我想在广告系列编辑表单中为选定帐户设置复选框.

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

我有这样的 Campaign 模型:

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.

我的表格是:

= 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

推荐答案

好的,我终于明白了,没有必要使用 has_many :通过很多人的推荐,这是我认为为选择添加复选框的最简单的设置HABTM 上的项目(有和属于多,多有多)关系.

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)

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

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

这篇关于带复选框的 Rails HABTM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆