I got a config with Cart
and CartItem
(belongs_to :cart
) models.
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
.
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>
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
The relevant Rails code is ActiveModel::Naming#model_name
and ActiveModel::Name#initialize
.
Now I finally get:
>> 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"
I think the same could work for Cart
instead of Cart::Cart
, with use_relative_model_naming?
on the Cart
class level.
You can declare the resources like this in your routes file.
resources :carts do
resources :cart_items, :as => 'items'
end
Refer to this section of the rails guide
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With