OneChillDude
OneChillDude

Reputation: 8006

Rails Self referential has_many through self

So I have a self referential rails model. In this model, a user has many friends, and all users have statuses. I would like for users to be able to get the statuses of other users. But I run into stack overflow errors because of recursive method calls.

class User
  has_many :statuses

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

end

I want to be able to say

class User
  has_many :statuses

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

however, this obviously creates a recursive call, which leads to SO. Is there any way I can get all of the friends statuses in a semantic, RESTful manner?

Upvotes: 0

Views: 497

Answers (2)

Manoj Monga
Manoj Monga

Reputation: 3083

Is creating association is mandatory? I think, you can fetch the friends' status in the controller itself. Something like:

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

and then you can just iterate through @friends to get the status as:

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

Hope it makes sense to you!

Upvotes: 1

Edward
Edward

Reputation: 3499

You could make a method in your user model like this

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

Not quite the way you wanted to do it, but I think it'd work.

Upvotes: 1

Related Questions