Rails 3选择标签

时间:2013-03-13 04:43:49

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我有一个产品型号,我需要从我的产品型号的其中一个列填充我的options_from_collection_for_select,但是我需要options_for_select是唯一的,而不是所有的值来自那一栏重复。

3 个答案:

答案 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')