This brings the comments with post_id=8
@onepost = Post.find(8)
@allpostsWithAssoc = @onepost.comments
But this doesn't bring the comments with post_id=8, but why ?
@onepost = Post.where(:id => 8)
@allpostsWithAssoc = @onepost.comments
I get
undefined method `comments' for #<ActiveRecord::Relation:0x9ecfce4>
The result of @onepost = Post.where(:id => 8)
is a collection (or Array) of all Post records which matched the condition, not the the record itself. try this:
@onepost = Post.where(:id => 8).first
@allpostsWithAssoc = @onepost.comments
.where
returns a relation. Even if you know that only one object matches the criteria, it is still a collection.
From the docs
The where method allows you to specify conditions to limit the records returned, representing the WHERE-part of the SQL statement. Conditions can either be specified as a string, array, or hash.
Try
@onepost = Post.where(:id => 8).first
@allpostsWithAssoc = @onepost.comments
to pick the first of (potentially numerous) matched records.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.