簡體   English   中英

Rails 4 collection_select從另一個模型

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM