Ruby on rails 仅列出唯一值
我有两个collection_select下拉菜单,当前设置如下:Ruby on rails 仅列出唯一值,ruby-on-rails,ruby-on-rails-3,drop-down-menu,Ruby On Rails,Ruby On Rails 3,Drop Down Menu,我有两个collection_select下拉菜单,当前设置如下: <div class="field"> <%= f.label :country_cont, "Country" %> <%= f.collection_select(:country_cont, Country.all, :country, :country) %> </div> <div class="field"> <%= f.la
<div class="field">
<%= f.label :country_cont, "Country" %>
<%= f.collection_select(:country_cont, Country.all, :country, :country) %>
</div>
<div class="field">
<%= f.label :city_cont, "City" %>
<%= f.collection_select(:city_cont, Job.all, :city, :city) %>
</div>
我希望下拉列表只显示数据库表中唯一值的列表(例如,在City中,而不是在London中显示5次,因为有5行包含我希望London只列出一次的城市)
如果您对此有任何建议,我们将不胜感激!:) 我会在您的工作类别中创建一个范围,按唯一城市进行筛选如何实际实现这一点取决于您的数据库。下面的示例使用MySQL语法:
class Job
scope :unique_by_city, lambda { select('DISTINCT(city)') }
end
在你看来
<div class="field">
<%= f.label :city_cont, "City" %>
<%= f.collection_select(:city_cont, Job.unique_by_city, :city, :city) %>
</div>
我会在你的职业类别中创建一个范围,按独特的城市进行过滤如何实际实现这一点取决于您的数据库。下面的示例使用MySQL语法:
class Job
scope :unique_by_city, lambda { select('DISTINCT(city)') }
end
在你看来
<div class="field">
<%= f.label :city_cont, "City" %>
<%= f.collection_select(:city_cont, Job.unique_by_city, :city, :city) %>
</div>
下面的答案还有一个更好的范围
下面的答案还有一个更好的范围
美好的忘了你能做到,太好了!我忘了你能做到。