Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 polymorphic_path - how to change the default route_key

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?

like image 917
Pandaamonium Avatar asked Jun 20 '12 20:06

Pandaamonium


2 Answers

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.

like image 145
Pandaamonium Avatar answered Nov 15 '22 10:11

Pandaamonium


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

like image 40
Salil Avatar answered Nov 15 '22 12:11

Salil