是否可以通过ROR中的属性或HAS_ONE关联来使一个属性相似



我想使用alias_attribute或类似于通过关联的属性类似的东西。我可以对delegate进行类似的操作,但是我必须委派所有生成的方法(attribute=attribute?等)。

是可能的:

class State < ApplicationRecord
  has_many :cities
end
class City < ApplicationRecord
  belongs_to :state
  alias_attribute :state_flag, :state.flag
end

我认为这里要做的最简单的事情是使用方法而不是别名。

类似:

class City < ApplicationRecord
  belongs_to :state
  def state_flag
    state.flag
end

然后,您可以致电:city.state_flag检索状态标志。

我很确定您与delegate陷入困境。好消息是您可以在一行上委派所有所需的方法。

belongs_to :state
delegate :flag, :flag=, to: :state, prefix: true

,如果您委派flag=,则需要记住保存关联的状态。

最新更新