Skip to content Skip to sidebar Skip to footer

Rails 4: Left Join Getting Values Of Joined Model

I have 3 models: class User < ActiveRecord::Base has_many :likes, :dependent => :destroy end class Movie < ActiveRecord::Base has_many :likes, :primary_key => :mid

Solution 1:

I think that Rails is not very good in giving explanatory exceptions, but you should try understanding them never the less:

# => undefined method `expanded' for #ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Like:0x007fae7ea51f48

So, this error tells you that there is no method expanded where you think it should be.

Nr. 1 reason for this sort of things are bugs in your own code!

A good programmer always thinks about what he or she might have done wrong, so let's look at your code:

m.likes.expanded

Here we have an object of class Movie. From the code you provided, we can see that it has_many likes. That's why there is an s to the end. It's not like but likes. So it is a list of objects. In this case, it is a lazily loaded Array of objects joined from the database. In Rails, those are handled by ActiveRecord::Associations::CollectionProxy.

So you are calling expanded on an instance of that proxy object, but instead, you would like to call it on an instance of Like.

If you want to do that, you need to iterate over those as well, or pick the one that is relevant, which might be the like that the current user did.

Post a Comment for "Rails 4: Left Join Getting Values Of Joined Model"