這是一個很難解釋的問題。所以這裏是一個例子。比方說,我在模型中有這樣的:has_many:通過:uniq關係需要收集通過表中的所有內容
has_many :things,
:through => :relationships,
:source => :thing
我需要和things
列表任何數據我對relationships
表。假設它是'relationships.name'。我們可以做這樣的:
has_many :things,
:through => :relationships,
:source => :thing,
:select => 'things.*, relationships.name as rel_name'
所以,如果有2個關係目前我會得到2個對象回來:
#<Thing id: 1, rel_name: "foo">
#<Thing id: 1, rel_name: "bar">
如果我們補習班:unique => true
或調整時,選擇使用DISTINCT
我們會得到獨特的對象,但關於其中一個關係的數據將會消失。我真正想要的是與收集到的所有訪問不同的關係名稱唯一things
:
#<Thing id: 1, rel_names: ["foo", "bar"] >
有一些黑暗魔法SQL我不知道的可以做到這一點?保持範圍對我來說很重要,所以我不能循環訪問結果集來收集數據。使用MySQL的GROUP_CONCAT
has_many :things,
:through => :relationships,
:source => :thing,
:select => 'things.*, GROUP_CONCAT(relationships.name as rel_name)'
是的!只是想念:group =>'things.id' – Grocery