Rails 3 polymorphic_path - how to change the default route_key

前提是你 提交于 2019-12-05 08:35:48

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

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