2016-10-03 45 views
0

我想作为列名使用如何使用options_from_collection_for_select帮助器返回不同的值?

options_from_collection_for_select() 

我有一个产品模型选择标签内恢复我的产品的国家,国家。我的代码看起来像这样

<%= select_tag(:country, options_from_collection_for_select(Product.all.order(:country), :id, :country), :prompt => "Alle Länder") %> 

但是,它给了我每个国家不止一次的下拉字段,即每个国家出现20次。

现在,我一直在试图使用一个类似的问题提出了解决,像这样

options_from_collection_for_select(Product.all.pluck('DISTINCT country'), :id, :country), :prompt => "Alle Länder") %> 

但是我得到一个错误,指出:

"undefined method `country' for "Spain":String 
Did you mean? count" 

现在我无法弄清楚哪些方法在这种情况下是适当的。

非常感谢!

+0

当你使用'pluck'你已经得到的字符串。此外,我想这个查询会给你产品的ID,而不是国家。也许你的模型应该有country_id而不是国名?你可以尝试'select_tag(:country,Product.all.pluck('DISTINCT country'))' –

回答

1

您将获得非uniq值,因为db中的行数多于给定国家/地区中的一行。

= f.select :country, 
    Product.pluck(:country).uniq, 
    { include_blank: 'Select country' } 

如果你想仍然使用select_tag

= select_tag :country, 
    options_for_select(Product.pluck(:country).uniq), 
    { include_blank: 'Select country' } 
+0

我假设你有'Country'模型,因为你选择的字段被称为'country_id' –

+0

这可能会很慢,因为你'重新从数据库中获取所有记录,然后让ruby处理重复数据删除。我认为OP想要在DB层处理这个问题(并且正确如此)。 –

+0

谢谢你的答案,但是我没有国家表:(可能只有一个国家表吗? – AaronDT