2017-07-31 65 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

希望這會有所幫助!