Rails自引用has_many通过自我

问题描述:

所以我有一个自引用rails模型。在这个模型中,用户有很多朋友,并且所有用户都有状态。我希望用户能够获取其他用户的状态。但是由于递归方法调用,我遇到了堆栈溢出错误。Rails自引用has_many通过自我

class User 
    has_many :statuses 

    has_many :friendships 
    has_many :friends, :through => :friendships 

end 

我希望能够说

class User 
    has_many :statuses 

    has_many :friendships 
    has_many :friends, :through => :friendships 
    has_many :friend_statuses, :through => :friends, :class_name => :statuses 
end 

然而,这显然是创建一个递归调用,从而导致SO。有什么方法可以以语义,RESTful的方式获取所有朋友的状态?

你可以做的方法在你的用户模型像你想要做这个

def friends_statuses 
    Status.where(user_id: friends.pluck(:id)) 
end 

不太方式,但我认为它会工作。

创建关联是强制性的吗?我想,你可以在控制器本身中获取朋友的状态。喜欢的东西:

@user = User.find(some_id_here) 
@friends = @user.friends.includes(:statuses) 

,然后你可以通过@friends只是重复,以获得尽可能状态:

@friends.each do |friend| 
    friend.status.each do |status| 
    #do something with friend and status 
    end 
end 

希望是有道理的你!

+0

雅,我试图避免无关的方法和迭代。但我想我必须这样做。 – OneChillDude 2013-03-04 15:17:26

+0

无论你使用什么方法,你都必须迭代通过朋友来获得他的状态。你唯一能做的就是减少查询次数,这就是我的例子。 – 2013-03-04 15:48:45