Pan*_*ium 6 routing ruby-on-rails-3
我得到了配置Cart和CartItem(belongs_to :cart)模型.
我想做的是打电话polymorphic_path([@cart, @cart_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>
Run Code Online (Sandbox Code Playgroud)
所以,为了重复我的问题,我能做些什么polymorphic_path([cart,cart.item])来寻找cart_item_path而不是cart_cart_item_path?
Pan*_*ium 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
Run Code Online (Sandbox Code Playgroud)
相关的Rails代码是ActiveModel::Naming#model_name和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"
Run Code Online (Sandbox Code Playgroud)
我认为同样可以用于工作Cart,而不是Cart::Cart与use_relative_model_naming?上Cart一流水平.
您可以在路由文件中声明这样的资源。
resources :carts do
resources :cart_items, :as => 'items'
end
Run Code Online (Sandbox Code Playgroud)
请参阅导轨指南的本节