mardi 14 novembre 2017

Ruby on rails - unable to create comments. NoMethodError

I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller

class CommentsController < ApplicationController
def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
end


private
    def comment_params
        params.require(:comment).permit(:body)
    end

end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
belongs_to :forum
end

Below is the form for section from the show.html.erb for the forum page

<h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>

And this is the error from rails:

undefined method `comment' for #

with the following extract:

end

        @comment = @forum.comment.create(comment_params) #highlighted

        redirect_to forum_path
    end

Aucun commentaire:

Enregistrer un commentaire