加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – Rails 3 polymorphic_path – 如何更改默认

发布时间:2020-12-16 21:14:39 所属栏目:百科 来源:网络整理
导读:我得到了Cart和CartItem(belongs_to:cart)模型的配置. 我想要做的是调用polymorphic_path([@ cart,@ car_item]),以便它使用cart_item_path而不是cart_cart_item_path. 我知道我可以将路由生成的url更改为/ carts /:id / items /:id,但这不是我感兴趣的内
我得到了Cart和CartItem(belongs_to:cart)模型的配置.

我想要做的是调用polymorphic_path([@ cart,@ car_item]),以便它使用cart_item_path而不是cart_cart_item_path.

我知道我可以将路由生成的url更改为/ carts /:id / items /:id,但这不是我感兴趣的内容.另外,将CartItem重命名为Item不是一个选项.我只想在整个应用程序中使用cart_item_path方法.

提前感谢任何提示!

只是为了表明我的观点:

>> app.polymorphic_path([cart,cart_item])
NoMethodError: undefined method `cart_cart_item_path' for #<ActionDispatch::Integration::Session:0x007fb543e19858>

那么,为了重复我的问题,我可以做些什么来使polymorphic_path([cart,cart.item])查找cart_item_path而不是cart_cart_item_path?

解决方法

在完成调用堆栈后,我想出了这个:
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

相关的Rails代码是ActiveModel::Naming#model_nameActiveModel::Name#initialize.

现在我终于得到:

>> cart.class
=> Cart::Cart(id: integer,created_at: datetime,updated_at: datetime)
>> cart_item.class
=> Cart::Item(id: integer,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"

我认为同样适用于Cart而不是Cart :: Cart,使用use_relative_model_naming?在Cart类级别.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读