【发布时间】:2015-07-19 07:41:07
【问题描述】:
我有文章和评论的简单场景。文章有 cmets。
在我的文章显示操作中,我显示文章和一个表单以添加评论。
提交评论时,它会触发 cmets#create 操作。
当保存成功时,它会重定向回文章显示操作。效果很好。
我的问题是当保存不成功时应该采取什么措施?
通常我会简单地使用:“render edit”,但是在这种情况下我没有 cmets#edit 操作。
class ArticlesController < ApplicationController
def show
@article Article.find(params[:id])
@comments = @article.comments.order(created_at: :asc).page(params[:page]).per_page(5)
@comment = Comment.new
end
end
class CommentsController < ApplicationController
def create
@article = Article.find(params[:id])
@comment = @article.comments.new(discussion_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to @article
else
render ???
end
end
private
def discussion_params
params.require(:comment).permit(:content)
end
end
_form.html.erb
<%= form_for([@article, Comment.new], html: { class: "comment-form", id: "comment-form" }) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_area :content, placeholder: "Add a comment...", rows: 3, minlength: 10, maxlength: 1000 %>
<button class="btn btn-success" type="submit">Post comment</button>
<% end %>
【问题讨论】:
-
你能发布你的文章展示动作吗?
标签: ruby-on-rails