jim
jim

Reputation: 9138

Rails combine two objects into one result hash

I have the following models in Rails: Users and *Friendship_Requests* friendship_requests contains user ids in the fields "from_user" and "to_user". I want to get a list of requests linked to a specific user from the requests model (which contains a message field also). I would also like the result to return the requesting users data that is held in the Users model.

In SQL I would use the following:

SELECT users.*, friendships_requests.*
FROM friendships_requests
JOIN users ON friendships_requests.from_user = users.id

Any ideas appreciated, thanks.

Upvotes: 2

Views: 544

Answers (1)

Alberto Santini
Alberto Santini

Reputation: 6564

To find the friendship requests sent to @user:

@friendship_requests = FriendshipRequests.find_by_to_user(@user.id)

and then the informations relative to the sending users can be retrieved as:

@friendship_requests.each do |request|
  user = User.find_by_id request.from_user
  # Do something
end

or, if you want to collect all of them

@users = @friendship_requests.map {|r| User.find_by_id r.from_user}

Upvotes: 2

Related Questions