【问题标题】:How do you pass validation errors across controllers?你如何跨控制器传递验证错误?
【发布时间】:2011-05-02 06:07:41
【问题描述】:

我正在 Rails 中创建一个常规论坛来练习。我有一个Topic 模型和一个嵌套的Post 模型。主题可以有很多帖子。

Topics#Show 有一个 @topic.posts 列表,然后是一个新的 Post 表单。

# Topics#Show
def show
  @topic = Topic.find(params[:id])
  @post = @topic.posts.new
end

提交新帖子发送至Posts#Create

# Posts#Create
  def create
    @topic = Topic.find(params[:topic_id])
    @post = @topic.posts.new(params[:post])
    @post.user = current_user
    if @post.save
      redirect_to @topic, :notice => "Successfully created post."
    else
      render :action => 'new' # <-- Unsure what to do here
    end
  end

如果帖子保存失败,我希望它呈现Topics#Show 并在那里显示验证错误。

据我了解,参数不会通过 redirect_to 持续存在,因为 302 重定向会启动新请求。

【问题讨论】:

    标签: ruby-on-rails-3


    【解决方案1】:

    您应该呈现主题/显示视图。所以不是

    render :action => 'new' # <-- Unsure what to do here
    

    做:

    render :template => 'topics/show'
    

    【讨论】:

    • 在主题#show 视图中,我使用&lt;%= render 'post_form' %&gt; 呈现帖子表单,这是部分topics/_post_form.erb。因此,当我从 topic#show 提交带有验证问题的帖子表单时,它给了我错误:Missing partial posts/post_form
    • 啊,我将topics/_post_form.erb 移动到posts/_form.erb 并让topics#show 渲染posts/form。当我提交表单时,我的网址从 topics/2 更改为 topics/2/posts。我没有帖子索引。有什么办法可以改变吗?
    • 你为什么要改变它?
    • Post 模型只存在于主题视图上显示。 topic#show 操作 (/topics/2) 是帖子的索引,出于我的意图。换句话说,我从不使用 Posts#Index。
    • Rails 不会将 /posts 附加到 /topics/2。表格提交至/topics/2/posts。如果没有错误,您将被重定向回/topics/2。如果有错误,请留在/topics/2/posts 并渲染视图以显示错误。
    【解决方案2】:

    使用render :template =&gt; "topics/show" 并确保设置@topic 变量的方式与您在TopicsController#show 操作中的设置方式相同。不过,您将无法从 PostsController 调用此 show 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2021-03-05
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      相关资源
      最近更新 更多