2015-02-10 81 views
0

例如,主題有很多評論,每個評論都屬於一個用戶。Rails:通過關聯收集?

我怎樣才能讓所有的用戶都有效地評論過這個主題?

現在我通過

@commenters = @topic.comments.collect do |post| 
    user = post.user 
    user 
end 

而且這樣做,我怎麼能做出@commenters uniq的?把它變成一個數組?

回答

1

您可以定義through關係

Rails through association

主題模型

class Topic < ActiveRecord::Base 
    ... 
    has_many :comments 
    has_many :users, 
    :through => :comments # add this line, it will enable association 
    ... 
end 

評價模型

class Comment < ActiveRecord::Base 
    .. 
    belongs_to :topic 
    belongs_to :user 
    .. 
end 

用戶模型

class User < ActiveRecord::Base 
    ... 
    has_many :comments 
    ... 
end 

然後你可以找到關於主題的用戶。

@topic.users 
+2

關於如何使它們成爲uniq,你希望在rails 4中has_many:users, - > {uniq},通過:: comments' – 2015-02-10 09:15:10