我有一个产品型号,我需要从我的产品型号的其中一个列填充我的options_from_collection_for_select
,但是我需要options_for_select
是唯一的,而不是所有的值来自那一栏重复。
答案 0 :(得分:0)
获取产品型号上特定列的唯一列表:
Product.uniq.pluck(:size)
答案 1 :(得分:0)
select_tag(name, option_tags = nil, options = {})
@uniq_products = Product.group(:column_name)
select_tag "product", options_from_collection_for_select(@uniq_products, "id", "<column_name>")
答案 2 :(得分:0)
虽然Rails提供了按唯一列值选择的方法,但使用find_by_sql
模型方法直接获取唯一结果会更快。
# app/controllers/products_controller.rb
@unique_products = Product.find_by_sql("SELECT * FROM products GROUP BY unique_column")
# app/views/products/_form.html.erb
<%= select_tag 'product', options_from_collection_for_select(@unique_products, 'id', 'name')