我有一个带有一些产品的 grouped_collection_select(链接到一个类别):
<%= c.grouped_collection_select :product_id, @categories, :products, :name, :id, :name, :include_blank => true %>
但我只想要一些具有“真”布尔值的产品,是否可以指定这个?
谢谢
我有一个带有一些产品的 grouped_collection_select(链接到一个类别):
<%= c.grouped_collection_select :product_id, @categories, :products, :name, :id, :name, :include_blank => true %>
但我只想要一些具有“真”布尔值的产品,是否可以指定这个?
谢谢
您基本上是在为分组选择中的每个父对象的实例调用一个方法。所以如果你有对应于你需要的产品的父对象(一个Category)的实例方法,你可以在helper中调用它。像这样的东西:
Class Category
has_and_belongs_to_many :products
def target_products
#return a collection here that corresponds to what you're looking for based on
#your criteria in the associated product(s) object. For example:
self.products.active #where active is a named scope in Product for what you're looking for.
#You could also add an AR macro method with a condition etc. Basically any thing that
#will respond to category.target_products in the end.
end
end
然后在您的 grouped_collection_select 中使用此方法。
<%= c.grouped_collection_select :product_id, @categories, :target_products, :name, :id, :name, :include_blank => true %>
为此,您需要根据该标准构建您的收藏。这意味着,@categories 将仅包含符合您条件的产品的那些类别。
(我正在对您的架构做出一些假设,但这样的事情应该可以工作:)
@categories = Category.where("products.some_attribute = ?", true).joins(:products)