Reputation: 610
I have four controllers - users, categories, stories and comments. My problem is with comments. When I submit a comment @comment.save is false and I can't understand where is the problem. My table in DB for Comment has content, user_id, story_id. Here is part of my code:
def new
@comment = Comment.new
@story = Story.find(params[:story_id])
end
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
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 %>
comment.rb:
class Comment < ActiveRecord::Base
attr_accessible :content, :story_id, :user_id
belongs_to :story
belongs_to :user
validates :content, :presence => true
validates :story_id, :presence => true
validates :user_id, :presence => true
default_scope :order => 'comments.created_at DESC'
end
story.rb
class Story < ActiveRecord::Base
attr_accessible :title, :content, :category_id
belongs_to :user
belongs_to :category
has_many :comments
validates :title, :presence => true
validates :content, :presence => true
validates :user_id, :presence => true
default_scope :order => 'stories.created_at DESC'
end
UPDATE When I use save! I have an error message Story cannot be blank.
Upvotes: 0
Views: 62
Reputation: 84114
You need to set the story for the comment your are building since (as you've obviously worked out), the story in question is given by params[:story_id]
. That story id isn't magically going to find its way into the params[:comment]
hash. You could either do
@comment = @story.comments.build(params[:comment])
@comment.user = current_user
or create the comment on the user and then set its story.
Upvotes: 1