6

我有一个带有CartCartItem( belongs_to :cart) 模型的配置。

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

我知道我可以将路由生成的 url 更改为/carts/:id/items/:id,但这不是我感兴趣的。此外,重命名CartItemItem不是一种选择。我只想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

4

2 回答 2

12

在一路向下调用堆栈之后,我想出了这个:

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, 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, 。use_relative_model_naming?Cart

于 2012-06-22T08:26:23.760 回答
2

你可以在你的路由文件中声明这样的资源。

resources :carts do
  resources :cart_items, :as => 'items'
end

请参阅导轨指南的这一部分

于 2012-06-22T02:48:49.237 回答