【问题标题】:render :new not going to the right place after a validationrender :new 验证后没有去正确的地方
【发布时间】:2012-01-08 05:26:31
【问题描述】:

我有一个在帖子模型中得到验证的“新”表单。当验证器启动时,它会错误地呈现。

新的帖子页面路径在'/posts/new'

在验证时,新的帖子页面路径位于“/posts”。我需要它返回到“/posts/new”。

这是我的控制器:

def create
 @post = current_user.posts.build(params[:post])
 if @post.save
   redirect_to public_post_page_path(@post.public_url)
 else 
   render :action => :new
 end
end

我觉得这可能与我的表格有关。所以这里是formtastic的第一行:

<%= semantic_form_for [:student, post], :html => {:id => "post_form"} do |form| %>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    这是 rails 的正确行为。

    在创建操作中,它只是呈现“新”视图文件。因此,url 将是 /posts,但视图将正确显示表单。这种行为没有错;一般来说,rails 约定是很好的形式。如果您只是渲染新的,那么内置的 rails 错误也会起作用;但是,如果您重定向它们将不会显示。

    如果你真的想回到你需要使用的那个网址:

    redirect_to 
    

    而不是渲染。

    【讨论】:

    • 我想显示错误,所以需要渲染。我需要它返回 /posts/new 的原因有点复杂。但基本上,在“def new”的控制器中,我检查用户的 twitter 验证以确定是否显示表单的某些部分。当它转到“/posts”时,我失去了这个验证。我想那么问题是,有没有办法在渲染后重新加载“新”控制器中的代码?
    • 创建一个私有控制器方法来为 new 进行设置,在它呈现新之前从 new 和 create 调用它
    • @Marc Rails,按照惯例,POST 对 /posts 进行创建。您可以随时通过发布到 /posts/new 来违反此约定。
    • 我听从了 house9 的建议。这样做了 'before_filter :check_twitter, :only => [:new, :edit, :create, :update]'
    • 这是一个重要的答案,因为如果你使用 Rspec 并且有这样的东西:page.current_url.should == "example.com/accounts/new",测试将失败,尽管实际行为是在 url /accounts 处,实际上正在呈现“新”。
    【解决方案2】:

    如果验证失败,用户应该会看到带有错误的表单并留在/posts/new。这就是你想要的,对吧?

    有一个简单的方法可以实现这一点。

    在表单上设置remote: true,防止url前进。处理 ajax:success 以将页面上的表单替换为新呈现的表单。

    $('form[data-remote=true]').on 'ajax:success', (e, data, status, xhr) ->
      if isHTML(data)
        thisForm = "form[id=#{@getAttribute('id')}]"
        $(thisForm).replaceWith $(data).find(thisForm)
    

    isHtml() 函数来自this question

    【讨论】:

      猜你喜欢
      • 2014-12-30
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多