So I’m still trying to work through a tutorial on building a CMS and
blog. I have a blog_controller.rb with post and comments. In my show
action, I’m trying to get it to pull the post with the given id and
then pull the collection of comments associated with that post’s id.
def show @post = Post.find(params[:id])
flash[:post_id][email protected]
@pages=Page.find(:all)
@posts=Post.find(:all)
@comments=Comment.find(params[@[email protected]])
end
Then I’m supposed to iterate over the comments in a partial view
_comment.rhtml:
<% @post_comments.each do |comment| %>
<%= render :partial=>“comment”, :object => comment %>
<% end %>
So I’m getting a NoMethod Error in the Show view. Anyone see the
(probably) obvious problem with the code? Also, is post_comments an
automatic variable created from a join table operation?
@post_comments does not get auto created. But if you have your model
relationships set you could do:
<% @post.comments.each do |comment| %>
<%= render :partial=>“comment”, :object => comment %>
<% end %>
In your Post model you’ll need
has_many :comments
That would simplify your code to
def show @post = Post.find(params[:id])
flash[:post_id][email protected]
@pages=Page.find(:all)
@posts=Post.find(:all)
end
So I’m getting a NoMethod Error in the Show view. Anyone see the
(probably) obvious problem with the code? Also, is post_comments an
automatic variable created from a join table operation?
flash[:post_id][email protected]
<% end %> @post_comments isn’t automatically created, which is probably why
you’re getting a no method error
also, i doubt
@comments=Comment.find(params[@[email protected]]) does what
you actually want it to.
If you want to show a particular post, then it is unlikely you would
need to load them all (@posts) and if the pages are related to the post,
then you can eager load them in the same find as the post: