dostrander
dostrander

Reputation: 747

ActiveRecord Joins

I'm just trying to use ActiveRecord to the best of it's ability and am having trouble doing joins in the way I would like.

Here is how my models are set up:

class Model
    has_many :likes
end

class Like
    belongs_to :model
    belongs_to :user
end

class User
    has_many :likes
end

I would like to get all the likes from a 'model' object and from there get all the users that made the like. So this is what my ActiveRecord query is

@model = Model.find(params[:id])
@users = @model.likes.joins(:user)

However, what that last line of code returns is a like, not a user. Is there any way to use joins appropriately and do what I want?

Thanks,
DO

Upvotes: 0

Views: 713

Answers (2)

scones
scones

Reputation: 3345

If you use the gem meta_where, you could use scope merging to get your data.

@users = User.scoped & (Like.scoped & Model.where(:id => params[:id]))

This returns an active_record relation object based on User, which you could for instance iterate over.

This is an alternative method to the one displayed by alfonso. His would also work.

Upvotes: 1

alf
alf

Reputation: 18530

You can do that with has_many :through:

class Model
    has_many :likes
    has_many :users, :through => :likes
end

Or you can eager load the users and do the join in ruby:

@users = @model.likes.includes(:user).map(&:user)

Upvotes: 3

Related Questions