2012-09-02 113 views
1

我有兩個collection_select下拉當前設置像這樣的菜單:只列出唯一值

<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> 

我想是下拉只能從我的數據庫表顯示唯一值的列表(例如在城市中,而不是在倫敦展示5次,因爲有5個行有該城市,我希望倫敦只列出一次)。

任何意見,將不勝感激! :)

回答

3

我會在您的作業類創建一個範圍,由獨特的城市進行過濾。 你如何實際執行這將取決於你的數據庫。下面的示例使用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> 

,如果你沒有在你的數據庫中大量的就業機會,只加載的所有記錄,做到在另一種版本是紅寶石:

class Job 
    def self.unique_by_city 
    all.uniq_by(&:city) 
    end 
end 
2

更好的範圍,下面的答案也see

class Job 
    scope :unique_by_city, lambda { select(:city).uniq} 
end 
+1

不錯!忘了你可以做到這一點。 –