Rails 3 polymorphic_path-如何更改默认的route_key [英] Rails 3 polymorphic_path - how to change the default route_key

查看:95
本文介绍了Rails 3 polymorphic_path-如何更改默认的route_key的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Cart CartItem belongs_to:cart )模型。

我要做的是调用 polymorphic_path([@ cart,@cart_item]) cart_item_path ,而不是 cart_cart_item_path

What I want to do is to call polymorphic_path([@cart, @cart_item]) so that it uses cart_item_path, instead of cart_cart_item_path.

我知道我可以将路线生成的url更改为 / carts /:id / items /:id ,但这不是我感兴趣的。而且,重命名 CartItem Item 是不可选项。我只想在整个应用程序中使用 cart_item_path 方法。

I know I can change the url generated by the route to /carts/:id/items/:id, but that's not what I'm interested in. Also, renaming CartItem to Item is not an option. I just want to use cart_item_path method throughout the app.

在此先感谢任何提示!

Thanks in advance for any tip on that!

只是为了阐明我的观点:

Just to make my point clear:

>> app.polymorphic_path([cart, cart_item])
NoMethodError: undefined method `cart_cart_item_path' for #<ActionDispatch::Integration::Session:0x007fb543e19858>

所以,重复我的问题,我该怎么做才能使 polymorphic_path ([cart,cart.item])来查找 cart_item_path 而不是 cart_cart_item_path 吗?

So, to repeat my question, what can I do in order for polymorphic_path([cart,cart.item]) to look for cart_item_path and not cart_cart_item_path?

推荐答案

在整个调用堆栈中完成之后,我想到了:

After going all the way down the call stack, I came up with this:

module Cart    
  class Cart < ActiveRecord::Base
  end  

  class Item < ActiveRecord::Base
    self.table_name = 'cart_items'
  end

  def self.use_relative_model_naming?
    true
  end

  # use_relative_model_naming? for rails 3.1 
  def self._railtie
    true
  end
end

相关的Rails代码为 code> ActiveModel :: Naming#model_name ActiveModel :: Name#initialize

The relevant Rails code is ActiveModel::Naming#model_name and ActiveModel::Name#initialize.

现在我终于明白了:

>> cart.class
=> Cart::Cart(id: integer, created_at: datetime, updated_at: datetime)
>> cart_item.class
=> Cart::Item(id: integer, created_at: datetime, updated_at: datetime)
>> app.polymorphic_path([cart, cart_item])
=> "/carts/3/items/1"
>> app.send(:build_named_route_call, [cart, cart_item], :singular)
=> "cart_item_url"

我认为 Cart 而不是 Cart :: Cart ,而 Cart上有 use_relative_model_naming? code>等级。

I think the same could work for Cart instead of Cart::Cart, with use_relative_model_naming? on the Cart class level.

这篇关于Rails 3 polymorphic_path-如何更改默认的route_key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆