Rails URL 在不更改视图的情况下进行更改
Rails URL changing without view changing
我正在 Rails 中测试一个应用程序,遇到了一个我无法弄清楚的故障。我有一个名为 "Families" 的 table,具有基本的 CRUD 功能。在新视图中创建新的 "family" 时,如果标题未通过验证,则应该重新渲染新视图。它是。但是 URL 从 "families/new" 变为 "families." 视图与 URL 不匹配。结果我的测试失败了。为什么我的 URL 会发生这种情况?这是我的测试:
require 'rails_helper'
feature "Creating a family" do
scenario "A user creates a family with invalid title" do
visit '/'
click_link 'Create Family'
click_button "Create"
expect(page.current_path).to eq(new_family_path)
end
end
这是我的控制器中的新建和创建操作:
def new
@family = Family.new
end
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
render :new
end
end
家庭模式:
class Family < ApplicationRecord
validates :title, presence: true
end
就在这里:
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
render :new
end
end
当您点击 create
动作时,您正在 POST
前往 families
。然后你 render :new
- 这让你在 families
url 和 new
部分显示。
如果您想在 families/new
url 结束,您需要做更多类似的事情:
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
redirect_to new_family_path
end
end
记住:渲染和路由是两个不同的东西。仅仅因为你 render :new
并不意味着你应该在 new_families_path
url 结束。两件事。
正在呈现视图,但是因为您点击 POST 端点 create
然后呈现 new
,POST 端点就是 url 显示。
不过,您可能不想在此处将其更改为重定向到 new
,因为您会丢失保存在 @family
对象中的数据,我假设您使用该对象显示表单上的用户输入。
我建议您改为检查表单是否再次呈现在页面上或是否显示了 flash 消息,而不是确认 url 是 /new
。
我正在 Rails 中测试一个应用程序,遇到了一个我无法弄清楚的故障。我有一个名为 "Families" 的 table,具有基本的 CRUD 功能。在新视图中创建新的 "family" 时,如果标题未通过验证,则应该重新渲染新视图。它是。但是 URL 从 "families/new" 变为 "families." 视图与 URL 不匹配。结果我的测试失败了。为什么我的 URL 会发生这种情况?这是我的测试:
require 'rails_helper'
feature "Creating a family" do
scenario "A user creates a family with invalid title" do
visit '/'
click_link 'Create Family'
click_button "Create"
expect(page.current_path).to eq(new_family_path)
end
end
这是我的控制器中的新建和创建操作:
def new
@family = Family.new
end
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
render :new
end
end
家庭模式:
class Family < ApplicationRecord
validates :title, presence: true
end
就在这里:
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
render :new
end
end
当您点击 create
动作时,您正在 POST
前往 families
。然后你 render :new
- 这让你在 families
url 和 new
部分显示。
如果您想在 families/new
url 结束,您需要做更多类似的事情:
def create
@family = Family.new(family_params)
if @family.save
redirect_to root_path
else
flash.now[:danger] = "There was a problem"
redirect_to new_family_path
end
end
记住:渲染和路由是两个不同的东西。仅仅因为你 render :new
并不意味着你应该在 new_families_path
url 结束。两件事。
正在呈现视图,但是因为您点击 POST 端点 create
然后呈现 new
,POST 端点就是 url 显示。
不过,您可能不想在此处将其更改为重定向到 new
,因为您会丢失保存在 @family
对象中的数据,我假设您使用该对象显示表单上的用户输入。
我建议您改为检查表单是否再次呈现在页面上或是否显示了 flash 消息,而不是确认 url 是 /new
。