Rails 3 polymorphic_path - how to change the default value of route_key

I got a configuration with Cart and CartItem ( belongs_to :cart ).

I want to do this to call polymorphic_path([@cart, @cart_item]) so that it uses cart_item_path instead of cart_cart_item_path .

I know that I can change the url generated by the route to /carts/:id/items/:id , but this is not what interests me. In addition, renaming CartItem to Item not an option. I just want to use the cart_item_path method throughout the application.

Thanks in advance for any feedback!

Just to understand my point:

 >> 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 to make polymorphic_path([cart,cart.item]) look for cart_item_path and not cart_cart_item_path ?

+6
source share
2 answers

After you completely lowered the call stack, I came up with the following:

 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 corresponding 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 be used for Cart instead of Cart::Cart , with use_relative_model_naming? at the Cart class level.

+12
source

You can declare resources like this in a routes file.

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

Refer to this section of the rail manual.

+2
source

Source: https://habr.com/ru/post/918595/


All Articles