Rails 3 polymorphic_path - how to change the default route_key

久未见 提交于 2019-12-07 03:38:44

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11127426/rails-3-polymorphic-path-how-to-change-the-default-route-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!