Just to confirm: David Underwood is correct that find_by
will make a database call. In fact, find_by
is basically just a wrapper for where
and take
, which will indeed make a DB call.
An alternative way to accomplish what you're looking for is to simply treat the collection proxy as an array, by using the find
method, like so:
@articles.each do |article|
logger.debug article.comments.find {|comment| comment.title == "Hello A"}
end
Update:
I have to admit, this one was a bit of a doozy.
The way to accomplish this in the manner you're looking for is to add another has_many
relationship that specifically contains the filtering condition you want, like so:
class Article < ActiveRecord::Base
has_many :hello_A_comments, -> { where(title: "Hello A") }, class_name: "Comment"
# rest of class
end
And then, you eager load using this new association, like so:
@articles = @current_user.articles.includes(:hello_A_comments)
This part is very important:
You now access the association not through the original :comments
association method, but through the new hello_A_comments
method instead, like so:
@articles.first.hello_a_comments
Unfortunately, as you can see, this method is not very dynamic, and sadly I do not know how to allow for variable conditions in the association in the case of eager loading. This answer might be a good resource to look at, but in the case of eager loading, honestly I don't believe its possible. If that is an issue, you might be stuck with the array method I mentioned earlier.