[英]Filtering a a collection in a 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_method
和text_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.