简体   繁体   English

Rails link_to可能嵌套的多态属性

[英]Rails link_to polymorphic attribute that is potentially nested

I have a Region > Store > Device hierarchy, where each of these things can have a config_set. 我有一个“区域”>“商店”>“设备”层次结构,其中每个事物都可以具有config_set。

class Region < ActiveRecord::Base
  has_many :stores, dependent: :destroy
  has_one :config_set, as: :configurable
end

class Store < ActiveRecord::Base
  has_many :devices
  has_one :config_set, as: :configurable
  belongs_to :region
end

class Device < ActiveRecord::Base
  has_one :config_set, as: :configurable
  belongs_to :store
end

class ConfigSet < ActiveRecord::Base
  belongs_to :configurable, polymorphic: true
end

From the config_set show page, I want to generate a link to whatever configurable that config_set belongs to. 从config_set show页面,我想生成一个指向config_set所属的可configurable的链接。 link_to is using polymorphic_url internally, which wants either a @device , a [@store, @device] , or a [@region, @store, @device] . link_to在内部使用polymorphic_url ,它需要使用@device[@store, @device][@region, @store, @device] Is there a simple way to deal with this? 有没有简单的方法来解决这个问题?

发现了一个不是很好的解决方案,它滥用了polymorphic_url @device[nil, @device]等效的事实,并结合了ruby的try

<%= link_to 'Back', [@config_set.configurable.try(:store).try(:region), @config_set.configurable.try(:store) || @config_set.configurable.try(:region), @config_set.configurable] %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM