我得到了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>
因此,重复我的问题,我该怎么做才能让
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_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"
我认为,对于
Cart
而不是Cart::Cart
,在use_relative_model_naming?
类级别上也可以使用Cart
。
关于ruby-on-rails-3 - Rails 3 polymorphic_path-如何更改默认的route_key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11127426/