不知道为什么在_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