我有四个控制器 - 用户,类别,故事和评论。我的问题是评论。当我提交评论@ comment.save是假的,我无法理解问题出在哪里。我在DB for Comment中的表有content,user_id,story_id。这是我的代码的一部分:
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
storiesController的show.html.erb:
<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
更新 当我使用保存!我有一条错误消息,故事不能为空。
答案 0 :(得分:1)
您需要为自己正在构建的评论设置故事(因为您显然已经解决了),有问题的故事由params[:story_id]
给出。那个故事ID并没有神奇地进入params[:comment]
哈希。你可以做
@comment = @story.comments.build(params[:comment])
@comment.user = current_user
或为用户创建评论,然后设置其故事。