Reputation: 610
I have some controllers - users, categories, stories and comments. Everything was okay till I did comments. In my DB I want to save content, user_id, story_id but the table is empty. @comment.save is false. Here is part of my code:
CommentsController:
def create
@story = Story.find(params[:story_id])
@comment = @story.comments.create(params[:comment])
if @comment.save
flash[:success] = "Successfull added comment"
redirect_to stories_path
else
render 'new'
end
end
show.html.erb for StoriesController:
<b><%= @story.title %></b> <br/><br/>
<%= @story.content %> <br/><br/>
<% @story.comments.each do |comment| %>
<b>Comment:</b>
<%= comment.content %>
<% end %>
<%= form_for([@story, @story.comments.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Add" %>
</div>
<% end %>
In StoriesController I did same thing but now I can't understand how to do it.
def create
@categories = Category.all
@story = current_user.stories.build(params[:story])
end
Upvotes: 0
Views: 162
Reputation: 610
I'm very stupid! I missed has_many comments in user model.. but now the problem is still here because the content of the comment can't be saved in DB and the table Comments is empty.
@comment.save is false in my case
def create
@story = Story.find(params[:story_id])
if current_user
@comment = current_user.comments.create(params[:comment])
end
if @comment.save
flash[:success] = "Successfull added comment"
redirect_to story_path(@story)
else
render 'new'
end
end
Upvotes: 0
Reputation: 2704
The error: "undefined method for nil:NilClass" always seems to bite me when I'm assuming that a model/class has been instantiated when it hasn't. If you are getting this error on the line:
@comment = current_user.comments.create(params[:comment])
I would guess that your code is being run without a logged-in user, so current_user is nil. The structure of your @comment code indicates that you are only going to let registered users create comments, so you might try this approach:
if current_user
@comment = current_user.comments.create(params[:comment])
else
redirect :root, :notice => "Sorry you must be registered and logged in to comment"
end
Hope this helps.
Upvotes: 0