2012-03-02 67 views
0

我有一些控制器 - 用户,类别,故事和注释。一切都很好,直到我做了评论。在我的数据库中,我想保存内容,user_id,story_id,但表格是空的。 @ comment.save是错误的。这里是我的代码部分:rails无法将结果保存在数据库中

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为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 %> 

在StoriesController我做同样的事情,但我现在不知道如何做到这一点。

def create 
    @categories = Category.all 
    @story = current_user.stories.build(params[:story]) 
end 
+0

哪一行明确导致错误假的?你是否在故事和评论之间建立了联系? – ellawren 2012-03-02 23:33:14

+0

我不知道如何,但当我重新启动服务器的错误消息的问题已修复,但评论表我DB是空的。我在story.rb has_many:评论和评论.rb - belongs_to:故事。在route.rb我: 资源:故事做 资源:评论 结束 – user1107922 2012-03-03 00:11:06

+0

现在我再次有错误消息..这行:@comment = current_user.comments.create(PARAMS [:评论]) – user1107922 2012-03-03 00:21:03

回答

1

的错误:“为无未定义的方法:NilClass”似乎总是要咬我,当我假设它没有在模型/类已被实例化。如果你上线了以下错误:

@comment = current_user.comments.create(params[:comment]) 

我猜想,你的代码正在没有登录的用户,因此CURRENT_USER为零运行。您@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 

希望这有助于。

+0

变更它是如何编写的,但当我登录时,问题仍然存在。并且错误消息位于此行,您猜测。 – user1107922 2012-03-03 12:01:38

0

我很愚蠢!我错过了用户模型中的has_many注释..但现在问题仍然存在,因为注释的内容无法保存在数据库中,表中的Comments是空的。

@ 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 
+0

需要尝试的一些事情:1)确保为注释添加了user_id列和belongs_to语句2)逻辑问题:当第一个if语句失败时,@comment变量不会被创建,第二个if语句的条件将生成异常。 3)确保你所有的注释字段都是attr_accessible--检查开发日志,看看你是否得到这个警告。 4)在代码中手动创建一个测试注释并尝试保存它(不要使用... create(params [:comment])5)puts()到服务器控制台params [:comment]看看你的表单正在发回给你。 – 2012-03-03 17:51:01