ruby-on-rails-3 – Rails 3 polymorphic_path – 如何更改默认的route_key

我得到了Cart和CartItem(belongs_to:cart)模型的配置.

我想要做的是调用polymorphic_path([@ cart,@ car_item]),以便它使用cart_item_path而不是cart_cart_item_path.

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

提前感谢任何提示

只是为了表明我的观点:

>> 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?

解决方法

在完成调用堆栈后,我想出了这个:
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代码ActiveModel::Naming#model_nameActiveModel::Name#initialize.

现在我终于得到:

>> cart.class
=> Cart::Cart(id: integer,created_at: datetime,updated_at: datetime)
>> cart_item.class
=> Cart::Item(id: integer,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,使用use_relative_model_naming?在Cart类级别.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...