form_form 和 path_prefix 中的自定义参数

发布于 2024-08-31 12:28:52 字数 1284 浏览 2 评论 0原文

我有这条路线:

# config/routes.rb
map.namespace :backshop, :path_prefix => '/:shop_id/admin' do |backshop|
  backshop.resources  :items
end

我想使用 form_for 魔法在以下两个视图上重用相同的表单:newedit 视图:

<% form_for [:backshop, @item] do |f| %>

这用于有效,并用于根据 @item 对象的状态构建创建项目的 url更新项目的 url

但这在这种情况下不起作用,因为没有 shop_id 参数,路由就不存在,而且我不知道如何对 form_for 说这样的话:

<% form_for [:backshop, @item], :shop_id => @shop do |f| %>

因为它尝试像 :shop_id 参数一样使用 @item

或者像这样

<% form_for [:backshop, @shop, @item] do |f| %>

因为它尝试构建这个网址:

backshop_shop_order_path

我知道我可以从部分中提取 form_for 声明,并根据 new进行不同的调用编辑:

<% form_for( @item, :url => backshop_items_path( @shop ) ) do |f| %>

<% form_for( @item, :url => backshop_item_path( @shop, @item ) ) do |f| %>

我只是想不要这样做,因为我有一堆模型,而且有点无聊:)

感谢

您的任何建议。

I have this route:

# config/routes.rb
map.namespace :backshop, :path_prefix => '/:shop_id/admin' do |backshop|
  backshop.resources  :items
end

And I want to use the form_for magic to reuse the same form on both: new and edit views:

<% form_for [:backshop, @item] do |f| %>

This used to works, and used to build a create url for the item or update url for the item depending on the status of the @item object.

But this is not working on this case because the routes don't exists without the shop_id parameter, and I don't know how to say to the form_for something like this:

<% form_for [:backshop, @item], :shop_id => @shop do |f| %>

Because it tries to use the @item like the :shop_id parameter.

Or like this

<% form_for [:backshop, @shop, @item] do |f| %>

Because it tries to build this url:

backshop_shop_order_path

I Know I can just to extract the form_for declaration from the partial and do different calls on depending if new or edit:

<% form_for( @item, :url => backshop_items_path( @shop ) ) do |f| %>

and

<% form_for( @item, :url => backshop_item_path( @shop, @item ) ) do |f| %>

But I just wanted don't do this because I have a bunch of models and is a few boring :)

Thanks for any suggestion

f.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

私藏温柔 2024-09-07 12:28:52

看起来您想使用名称空间进行嵌套资源,也许您可​​以将路线重写为类似

map.namespace(:admin) do |admin|
  admin.resources :shops do |admin_shop|
     admin_shop.resources :item
  end
end

现在您应该能够使用 [@shop, @item] 来获取您想要的路线。使用rake paths来检查路由并看看它们是否符合您的喜好。

Looks like you want to do nested resources with a namespace maybe you can rewrite your routes to something like

map.namespace(:admin) do |admin|
  admin.resources :shops do |admin_shop|
     admin_shop.resources :item
  end
end

Now you should be able to use [@shop, @item] to get the route you want. Use rake routes to examine the routes and see if they are to your liking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文