Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 Rails 3多态路径-如何更改默认路由密钥_Ruby On Rails 3_Routing - Fatal编程技术网

Ruby on rails 3 Rails 3多态路径-如何更改默认路由密钥

Ruby on rails 3 Rails 3多态路径-如何更改默认路由密钥,ruby-on-rails-3,routing,Ruby On Rails 3,Routing,我得到了一个带有购物车和购物车项目(属于:购物车)模型的配置 我想做的是调用多态路径([@cart,@cart\u item]),以便它使用cart\u item\u路径,而不是cart\u cart\u item\u路径 我知道我可以将路由生成的url更改为/carts/:id/items/:id,但这不是我感兴趣的。此外,将CartItem重命名为Item也不是一个选项。我只想在整个应用程序中使用cart\u item\u path方法 提前感谢您提供的任何提示 我想说清楚: >>

我得到了一个带有
购物车
购物车项目
属于:购物车
)模型的配置

我想做的是调用
多态路径([@cart,@cart\u item])
,以便它使用
cart\u item\u路径
,而不是
cart\u cart\u item\u路径

我知道我可以将路由生成的url更改为
/carts/:id/items/:id
,但这不是我感兴趣的。此外,将
CartItem
重命名为
Item
也不是一个选项。我只想在整个应用程序中使用
cart\u item\u path
方法

提前感谢您提供的任何提示

我想说清楚:

>> app.polymorphic_path([cart, cart_item])
NoMethodError: undefined method `cart_cart_item_path' for #<ActionDispatch::Integration::Session:0x007fb543e19858>
>应用程序多态路径([购物车,购物车项目])
NoMethodError:未定义的方法“cart\u cart\u item\u path”#

那么,重复我的问题,为了让多态路径([cart,cart.item])查找
cart\u item\u路径而不是
cart\u cart\u item\u路径
,我可以做些什么?

您可以在路由文件中这样声明资源

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

请参阅

在经历了整个调用堆栈之后,我得出了以下结论:

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

我认为这同样适用于
Cart
而不是
Cart::Cart
,在
Cart
类级别上使用
相对模型命名?

这正是我正在做的。如果你仔细阅读,这就是问题所在,因为:
>app.polymorphic_path([cart,cart.item])
NoMethodError:undefined method
cart_cart_item_path',for#`那么,重复我的问题,我能为polymorphic_path([cart,cart.item])做些什么寻找购物车项目路径而不是购物车项目路径?这个答案救了我一天,谢谢!请注意,它还影响表单中的参数名称,例如,
Cart::Item.model_name.param_key
'Cart\u Item'
更改为
'Item'
>> 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"