Suppose I have the following models:
class Post < ActiveRecord::Base has_many :authors class Author < ActiveRecord::Base belongs_to :post
And let the Author model have a name attribute.
I want to find all posts with the specified author "alice" by this author name. Say there is another author of "bob" who co-authored a post with Alice.
If I search for the first result using includes and where :
post = Post.includes(:authors).where("authors.name" => "alice").first
You will see that the message has only one author, even if in fact there are more:
post.authors #=> [#<Author id: 1, name: "alice", ...>] post.reload post.authors #=> [#<Author id: 1, name: "alice", ...>, #<Author id: 2, name: "bob", ...>]
It seems that the problem is related to the combination of includes and where , which correctly limits the area for the required record, but at the same time hides all associations, except that it matches.
I want to end up using ActiveRecord::Relation for the chain, so the above reload solution is not really satisfactory. Replacing includes with joins solves this, but does not require loading associations:
Post.joins(:authors).where("authors.name" => "alice").first.authors #=> [#<Author id: 1, name: "alice", ...>, #<Author id: 2, name: "bob", ...>] Post.joins(:authors).where("authors.name" => "alice").first.authors.loaded? #=> false
Any suggestions? Thanks in advance, I banged my head on this issue for a while.