2013-03-26 50 views
0

我对表示朋友的用户模型有标准的自引用关系。该部分工作正常,但我在连接表中有一个额外的列表示该关系的来源。过滤在Ruby on Rails的连接表上有很多值的关系

友谊型号

# Relationships 
belongs_to :user 
belongs_to :friend, :class_name => "User" 
has_one :source 

用户模型

has_many :friendships 
has_many :friends, :class_name => "User", :through => :friendships 

我明白,我可以在我的用户的朋友

user.friends.where([some conditions]) 

我的问题是,如何获取做了其中过滤器在友谊中通过:源关系过滤的用户对象“朋友”列表?

回答

0

只是想出了这一点。万一有人好奇。

用户模型

has_many :friendships 
has_many :friends, :class_name => "User", :through => :friendships do 
    def bySource(sourceId) 
     where("friendships.source_id = ?", sourceId) 
    end 
end 

使用

users.friends.bySource(1) 
+0

您甚至不必这样做。您可以在名为'by_source'的友谊模型上放置作用域,并以完全相同的方式调用它。 – 2013-03-26 17:57:29

+0

听起来不错,我可以根据每个来源定义一个范围。我能举一个例子吗? – smokingoyster 2013-03-26 18:27:04