2011-11-03 18 views
3

這是一個很難解釋的問題。所以這裏是一個例子。比方說,我在模型中有這樣的: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)' 

回答

1

的MySQL有GROUP_CONCAT()方法,這樣的事情

class MyModel < ActiveRecord::Base 
    attr_accessor :rel_names 

    has_many :things, 
    :through => :relationships, 
    :source => :thing, 
    :select => 'things.*, GROUP_CONCAT(DISTINCT relationships.name SEPARATOR ";;") as rel_names' 


    # .. your code .. 

    def rel_names 
    @rel_names.present? ? @rel_names.split(';;') : [] 
    end 
end 
+0

是的!只是想念:group =>'things.id' – Grocery