【问题标题】:Rails Nested form validation errorsRails 嵌套表单验证错误
【发布时间】: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


【解决方案1】:

试试这个。

 render 'articles/show'

【讨论】:

  • 我猜我在文章#show 操作中定义的任何实例变量都需要在 cmets#create 操作中复制,否则视图将无法使用它们。例如,articles#show 操作包括 @cmets,它是现有 cmets 的列表,但在 cmets#create 操作中没有定义。
  • 是的,您需要您在文章#show 中定义的那些实例变量,以防您的评论未保存。保持在其他条件下。抱歉,我不知道文章显示操作,所以我只是添加渲染行作为答案。
  • 优秀。页面现在重新加载,但验证错误未按预期显示。我会将我的 for 添加到原始问题中。
  • 没有显示验证错误,因为您正在重新初始化评论。 Comment.new 表单中的错误将被删除。在 post show 操作中初始化 @comment = Comment.new 并在表单中使用它作为标签。我希望这会奏效。
  • 你是 100% 正确的。我没有在控制器中初始化 @comment 的原因是因为它在我的表单中歪曲了评论计数。当我有一篇没有 cmets 的文章时,评论计数正确显示为零,但是当保存失败并呈现显示操作时,评论计数显示为 1。我之前曾询问过这个问题:stackoverflow.com/questions/31018338/…
【解决方案2】:

create 动作是从 new.html 页面执行的?然后你可以使用:

render :new

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多