簡體   English   中英

用於關系模型的options_from_collection_for_select

[英]options_from_collection_for_select for relational model

我有兩個模型,具有has_many關聯的Customer和Product。

我要使用options_from_collection_for_select顯示每個客戶的產品名稱。 我想在下面做這樣的事情

<%= select_tag(:customer_product, options_from_collection_for_select(@customers, @customers.products.id, @customers.products.name) )%>

要么

  <%= select_tag(:customer_product, options_from_collection_for_select(@customers,:product.id, :product.name) )%>

我嘗試了第二個並收到此錯誤

undefined method `id' for :product:Symbol

我想知道這樣的事情是否可行。 或如何輕松實現上述功能。

嘗試這個:

options_from_collection_for_select(@customers.products, 'id', 'name')

第一個參數是項目的集合,第二個和第三個參數是返回id和文本的屬性的名稱。

參考: http : //apidock.com/rails/v4.2.1/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

options_from_collection_for_select所述options_from_collection_for_select期望將collection作為第一個參數,將value_methodtext_method作為第二和第三個參數,將在collection上調用該參數。

如果將@customers作為第一個參數傳遞,則只能將Customer的屬性作為第二個和第3個傳遞,如下所示:

<%= select_tag(:customer_product, options_from_collection_for_select(@customers, 'id', 'name') )%>

如果您需要傳遞@products則首先需要通過ruby設置@products ,例如:

@products = @customers.inject([]).each do |all_products, customer_products|
  all_products << customer_products
end.flatten.uniq

或者,根據您的邏輯,甚至可以通過sql本身。

然后使用以下內容進行查看:

<%= select_tag(:customer_product, options_from_collection_for_select(@products, 'id', 'name') )%>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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