当动作" new"时,Rails在验证失败后不保留URL参数。被渲染

时间:2015-03-27 05:15:59

标签: ruby-on-rails forms validation url-parameters

当我使用此网址创建产品时 http://localhost:3000/versions/new?product_id=1 并且验证失败,Rails不会将product_id保留在URL

我得到了这个网址 http://localhost:3000/versions

我需要该参数来按产品和#34;返回"这样的链接保留过滤器,但我不想使用"会话"或"重定向"这样做。

我不明白为什么Rails不保留网址。我之前使用过CakePHP表格,参数和验证,我确信我没有遇到过这个问题。

def create
    @version = Version.new(version_params)
    respond_to do |format|
        if @version.save
            format.html { redirect_to @version, notice: I18n.t('controllers.versions.created_successfully', default: 'Version was successfully created.') }
            format.json { render :show, status: :created, location: @version }
        else
            format.html { render :new }
            format.json { render json: @version.errors, status: :unprocessable_entity }
        end
    end
end

谢谢。

1 个答案:

答案 0 :(得分:0)

首先让我解释为什么会发生这种情况

表单发布到versions_path /versions,当验证失败时,rails(默认情况下)不会重定向回来,而是在同一路径中呈现,即{{1}就像你说的那样,你可以从this guide找到更多关于CRUD路线的信息。

在你的情况下,我认为它更适合create a nested resource,所以网址更像是/versions, 在路线文件中,它看起来像这样

/products/1/versions/new

这样,当验证失败时,您将被重定向到resources :products resources :versions end ,该product_versions_path将映射到/products/1/versions,您仍然可以访问变量中的产品ID 1params[:product_id]