0

I am using rails 2.3.5. I have a Blog model and Blog has many comments. This is my Blog controller show action

def show
  @blog = Blog.find(params[:id])
  @comment = Comment.new
end

I would display the Blog and at the end would have an option for creating comment. So I add this in blogs/show.html.erb.

<% form_remote_for  @comment do |f| %>
      <%= f.label :content %>
      <%= f.text_area :content, :rows => 6 %>
      <%= f.hidden_field :blog => @blog %>
      <%= f.submit %>
  <% end %>    

But i get the following error when i run this NoMethodError in Blogs#show

Showing app/views/blogs/show.html.erb where line #270 raised:

undefined method `blog#<Blog:0xb677d8d0>' for #<Comment:0xb67762b0>

Extracted source (around line #270):

0

3 Answers 3

2

Comment model should have belongs_to :blog

Blog model should have has_many :comments

Initialize the comment in the controller like this:

@blog.comments.new

The view should be like this:

<%= f.hidden_field :blog_id %>
Sign up to request clarification or add additional context in comments.

1 Comment

to '@comment' only with '@comment = @blog.comments.build'
1

you have to hide the id of the blog not the blog object.

<%= f.hidden_field :blog_id%>

Comments

0

The problem is your f.hidden_field line. The first parameter should be the attribute name of the @comment you want in the field, but in your code it's a Hash.

I'd suggest adjusting your show action to set @comment = @blog.comments.build, and change the view to read f.hidden_field :blog_id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.