不知道爲什麼在_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
因爲評論沒有保存。爲了快速修復,請用'@ comment.save!'替換'@ comment.save',您將看到爲什麼無法保存。 (_我打賭一些存在驗證不符合) –
也不要從參數中取出article_id。執行此操作:'@ article.comments.create(params.require(:comment).permit(:content,:user_id))'(在評論表單中對'user_id'也有一個隱藏字段) –
謝謝!是的,這是因爲驗證沒有得到滿足。 – doyz