删除select params数组中的重复字符串

时间:2017-10-30 08:39:22

标签: ruby-on-rails ruby forms

我知道删除select form_tag params中所有重复字符串的最佳方法。

我尝试了.uniq.distinct但是,它不起作用。

<%= select_tag(:city, options_for_select(@customers.where(user: current_user).collect{ |b| [b.city, b.city]}), {:prompt => "City", :class => "form-control select-search"}) %>

我的select_tag为每位客户提供相同的城市。

1 个答案:

答案 0 :(得分:1)

使用collect(map)代替ActiveRecord查询结果,您可以使用pluck这样返回一个包含所选属性的数组,然后您可以使用uniq,就像:

Customer.where('user = ?', current_user).pluck(:city).uniq
# ['city1', 'city2', 'city3']

注意pluck和distinct也可以一起使用,它会将DISTINCT语句添加到查询中,并避免将uniq方法链接到其结果:

Customer.where('user = ?', current_user).pluck('DISTINCT city')
# ['city1', 'city2', 'city3']

Customer.where('user = ?', current_user).distinct.pluck(:city)
# ['city1', 'city2', 'city3']
相关问题