2017-07-31 59 views
0

不知道为什么在_comment_form.html.erb创建的意见没有被呈现在文章/:ID评论不保存到数据库

我引用此YouTube教程:https://www.youtube.com/watch?v=IUUThhcGtzc

评论控制器:

class CommentsController < ApplicationController 
    before_action :authenticate_user! 
    before_action :set_article 

    def create 
    @comment = @article.comments.create(params[:comment].permit(:content, :article_id, :user_id)) 
    @comment.user = current_user 
    @comment.save 
    if @comment.save 
     redirect_to @article 
    else 
     redirect_to @article 
    end 
    end 

    private 

    def set_article 
     @article = Article.find(params[:article_id]) 
    end 

end 

文章控制器:

class ArticlesController < ApplicationController 
    before_action :authenticate_user!, except: [:index, :show] 
    before_action :set_article, only: [:show, :edit, :update, :destroy] 

    def show 
    @comments = Comment.where(article_id: @article).order("created_at DESC") 
    end 

    private 

    def set_article 
     @article = Article.find(params[:id]) 
    end 
end 

_comment.html.erb(从文章/ show.html.erb)

<%= render 'comments/comment_form' %> 

    <% @comments.each do |comment| %> 
     <%= comment.content %> 
    <% end %> 

_comment_form.html.erb

<% if user_signed_in? %> 
    <%= form_for ([@article, @article.comments.build]) do |f| %> 
    <div class="form-group"> 
     <%= f.label :content %> 
     <%= f.text_area :content, class: 'form-control' %> 
    </div> 

    <%= f.submit 'Post Comment', class: 'btn btn-primary' %> 
    <% end %> 
<% end %> 

的routes.rb

resources :articles do 
    resources :comments 
    end 
+0

因为评论没有保存。为了快速修复,请用'@ comment.save!'替换'@ comment.save',您将看到为什么无法保存。 (_我打赌一些存在验证不符合) –

+0

也不要从参数中取出article_id。执行此操作:'@ article.comments.create(params.require(:comment).permit(:content,:user_id))'(在评论表单中对'user_id'也有一个隐藏字段) –

+0

谢谢!是的,这是因为验证没有得到满足。 – doyz

回答

0

一些考虑,我想要做:

@comment.save 
if @comment.save 

当你d o那,你节省了两次。如果条件已经保存文章,则调用@comment.save,如果成功则返回truefalse。另外,替换.save.save!,所以它会引发一个异常,如果它不保存,所以你可以检查rails服务器日志的原因。

此外,认为这是没有必要做到这一点:

@comments = Comment.where(article_id: @article).order("created_at DESC") 

既然你已经设置的@article,您可以访问@article.comments,一旦你把has_many :comments上的文章模型。

如果文章已正确创建,您还可以在导轨控制台上进行检查。创建一个新的,并得到它像article = Article.last,那么你可以检查article.comments

希望这会有所帮助!