【问题标题】:Passing validation errors array from one controller to another将验证错误数组从一个控制器传递到另一个控制器
【发布时间】:2018-06-16 23:07:14
【问题描述】:

我有 Comment belongs_to PostPost has_many Comments,评论模式如下:

class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :user
  validates :text, presence: true
end

添加新cmets的表单位于Posts显示视图,如下:

<%= form_with(model: [ @post, @post.comments.build ], local: true) do |form| %>
    <% if @comment.errors.any?%>
        <div id="error_explanation">
          <ul>
            <% @comment.errors.messages.values.each do |msg| %>
              <%msg.each do  |m| %>
                 <li><%= m %></li>
              <%end %>
             <% end %>
          </ul>
        </div>
    <% end %>
    <p>
       <%= form.text_area :text , {placeholder: true}%>
    </p>

    <p>
       <%= form.submit %>
    </p>
<% end %>

评论创建动作,如下:

class CommentsController < ApplicationController

def create
    @post = Post.find(params[:post_id])
    @comment = Comment.new(comment_params)
    @comment.post_id = params[:post_id]
    @comment.user_id = current_user.id
    if @comment.save
        redirect_to post_path(@post)
    else
        render 'posts/show'
    end
end



private
    def comment_params
      params.require(:comment).permit(:text)
    end
end

我需要渲染帖子/显示页面以显示 Comment 验证错误,但问题是我在 CommentsController 控制器中而不是 PostsController 所以页面中使用的所有对象/show 视图将为空。

如何将@comment 对象传递给页面/显示? 我想过使用 flash 数组,但我正在寻找更传统的方式。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    是的,渲染pages/show 将只使用视图模板,而不是操作,因此您在pages#show 控制器操作中定义的任何内容都将不可用。 @comment 将可用,但正如您在 comments#create 操作中定义的那样。如果没有看到PostsController,我不知道您在pages#show 操作中还加载了什么——您可以考虑将两者中所需的任何内容移动到ApplicationController 上的方法中,然后从这两个地方调用。另一种选择是将您的评论过程更改为通过 AJAX 工作(remote: true 而不是表单上的local: true),并使用旨在重新呈现评论表单的 JS 进行响应(您可以将其移动到部分使用两者在pages/show.html.erbcomments#create 响应中)。

    上面代码中的一些其他注释 - 在comments#create 中,您可以使用:

    @comment = @post.comments.new(comment_params)
    

    为了避免需要手动在@comment 上设置post_id

    对于表单,我很想在pages#show 中设置新评论:

    @comment = @post.comments.build
    

    然后在表单中引用它,如果您在pages#showcomments#create 之间重复使用它会更容易:

    <%= form_with(model: [ @post, @comment ], local: true) do |form| %>
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多