Rails 4 : 自定义路由,单个模型的多个编辑表单
Rails 4 : Custom routes, multiple edit forms for a single model
我有一个 Rails 4 应用程序,它的事物模型具有 3 个属性:attr_1、attr_2、attr_3。
我想要两个编辑表单:
- 第一个会更新 attr_1 和 attr_2
- 第二个只会更新attr_3
我在我的things_controller.rb中写了四个方法:
def edit
#edit form for attr_1 & attr_2
end
def edit_attr_3
#edit form for attr_3 only
end
def update
#update attr_1 & attr_2
end
def update_attr_3
#update attr_3 only
end
这是我的 routes.db
resources :things do
member do
get :edit_attr_3
put :update_attr_3
end
end
现在,GET 到两个编辑视图都有效(/things/:id/edit 和 /things/:id/edit_attr_3)但是在提交时,thing#update 表单是两次调用(thing#update_attr_3 从未被调用)
我怎样才能继续获取链接到 thing#edit_attr_3 的操作#update_attr_3?
编辑:
回答,感谢Ross & Steve Klein :
在我看来,我正在使用 bootstrap_form_for。通常 :url 参数是可选的,因为标准 edit/update 是按照约定链接的。如果是自定义编辑或更新动作,需要指定更新路径。
<%= bootstrap_form_for @thing, url: update_attr_3_thing_path(@thing) do |f| %>
<% end %>
如果没有看到你的表单代码很难说...但是如果你使用 form_for
那么在这两种情况下它都会映射到更新操作的路由(对象不是新对象)。
要使其与您独特的更新操作一起使用,您必须指定 form_for
应该使用的 url。类似于:
<%= form_for @thing, url: things_update_attr_3_path(@thing) do |f| %>
# other form stuff .......
您可以在命令提示符下使用 bundle exec rake routes
来查看您当前的路由是什么,以便您现在可以将路由助手与表单一起使用。
我有一个 Rails 4 应用程序,它的事物模型具有 3 个属性:attr_1、attr_2、attr_3。
我想要两个编辑表单:
- 第一个会更新 attr_1 和 attr_2
- 第二个只会更新attr_3
我在我的things_controller.rb中写了四个方法:
def edit
#edit form for attr_1 & attr_2
end
def edit_attr_3
#edit form for attr_3 only
end
def update
#update attr_1 & attr_2
end
def update_attr_3
#update attr_3 only
end
这是我的 routes.db
resources :things do
member do
get :edit_attr_3
put :update_attr_3
end
end
现在,GET 到两个编辑视图都有效(/things/:id/edit 和 /things/:id/edit_attr_3)但是在提交时,thing#update 表单是两次调用(thing#update_attr_3 从未被调用)
我怎样才能继续获取链接到 thing#edit_attr_3 的操作#update_attr_3?
编辑:
回答,感谢Ross & Steve Klein :
在我看来,我正在使用 bootstrap_form_for。通常 :url 参数是可选的,因为标准 edit/update 是按照约定链接的。如果是自定义编辑或更新动作,需要指定更新路径。
<%= bootstrap_form_for @thing, url: update_attr_3_thing_path(@thing) do |f| %>
<% end %>
如果没有看到你的表单代码很难说...但是如果你使用 form_for
那么在这两种情况下它都会映射到更新操作的路由(对象不是新对象)。
要使其与您独特的更新操作一起使用,您必须指定 form_for
应该使用的 url。类似于:
<%= form_for @thing, url: things_update_attr_3_path(@thing) do |f| %>
# other form stuff .......
您可以在命令提示符下使用 bundle exec rake routes
来查看您当前的路由是什么,以便您现在可以将路由助手与表单一起使用。