[英]How to use collection_select in rails 4 from a model module?
[英]Rails 4 collection_select from another model
我的模型具有以下(相关)声明:
class Campaign < ActiveRecord::Base
has_many :placements, dependent: :destroy
has_many :clients, dependent: :destroy
accepts_nested_attributes_for :clients, allow_destroy: true
accepts_nested_attributes_for :placements, allow_destroy: true
end
class Placement < ActiveRecord::Base
has_one :client, through: :campaign
belongs_to :campaign
validates_presence_of :hashtags_instagram, :hashtags_twitter, :sms, :url, :channel
end
class Client < ActiveRecord::Base
belongs_to :campaign
belongs_to :placement
validates_presence_of :client_name
end
因此,广告系列具有许多有效的展示位置和客户。 展示位置仅具有一个客户,并且仅与一个广告系列相关联(或者至少应该如此,我不确定我是否正确地做到了这一点)。
因此,在我的展示位置表单中,我希望它显示一个属于该展示位置广告系列的所有客户的下拉菜单(并非所有广告系列)。 如果是新的展示位置,则应显示“请选择或类似内容”,否则,应显示属于该展示位置的客户。
我似乎无法使:prompt选项正常工作。 它从不实际显示“请选择”,仅显示列表中的第一个客户端。 我试图用它来使其工作:
奇怪的是,如果我将提示符更改为include_blank,它实际上会显示空白项目(尽管它仍然选择列表中的第一个客户端,而不是空白项目)。
当我尝试了一些事情时,我尝试了代码:
= f.collection_select(:placement_id, @placement.client.all.to_a, :id, :client_name, {:prompt => true}, class: "newdropdown-menu", id: "newdropdown")
并得到错误信息:
Could not find the source association(s) :client or :client in model Campaign. Try 'has_many :client, :through => :campaign, :source => <name>'. Is it one of :user, :placements, :clients, or :photo?
如果我更改集合,请选择以下内容:
= f.collection_select(:campaign_id, @placement.campaign.clients.all.to_a, :id, :client_name, {:prompt => true}, class: "newdropdown-menu", id: "newdropdown")
然后它运行,但实际上不显示提示,仅显示列表。
将@placement更改为placement似乎没有任何效果(这似乎很奇怪)。
我不想将其更改为has_many,因为展示位置应具有一个客户端。 我应该如何进行? 我试图弄乱:source,但似乎与我的问题无关。
您需要将html选项放在哈希中:
f.collection_select(:campaign_id, @placement.campaign.clients.all, :id, :client_name, {:prompt => true}, {class: "newdropdown-menu", id: "newdropdown"})
可在此处找到文档: http : //apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.