我有一些控制器 - 用户,类别,故事和评论。一切都没问题,直到我做了评论。在我的数据库中,我想保存内容,user_id,story_id,但表格为空。 @ comment.save是假的。这是我的代码的一部分:
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
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 %>
在StoriesController中,我做了同样的事情,但现在我无法理解如何做到这一点。
def create
@categories = Category.all
@story = current_user.stories.build(params[:story])
end
答案 0 :(得分:1)
错误:“nil的未定义方法:NilClass”当我假设模型/类已经实例化时,似乎总是咬我。如果您收到此错误:
@comment = current_user.comments.create(params[:comment])
我猜你的代码是在没有登录用户的情况下运行的,所以current_user是nil。 @comment代码的结构表明您只是让注册用户创建注释,因此您可以尝试这种方法:
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
希望这有帮助。
答案 1 :(得分:0)
我很傻!我错过了用户模型中的has_many注释..但现在问题仍然存在,因为注释的内容无法保存在DB中,表注释为空。
在我的案例中,@ comment.save是假的
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