简体   繁体   中英

Is it possible to alias an attribute through a belongs_to or has_one association in RoR?

I'd like to use alias_attribute or something similar to alias an attribute through an association. I can do something similar with delegate , but I have to delegate all of the generated methods ( attribute= , attribute? , etc.).

Is something like this possible:

class State < ApplicationRecord
  has_many :cities
end

class City < ApplicationRecord
  belongs_to :state

  alias_attribute :state_flag, :state.flag
end

I think the simplest thing to do here is to use a method instead of an alias.

Something like:

class City < ApplicationRecord
  belongs_to :state

  def state_flag
    state.flag
end

Then, you'll be able to call: city.state_flag to retrieve the state flag.

I'm pretty sure you're stuck with delegate for this. The good news is you can delegate all the methods you need on a single line.

belongs_to :state

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

You'll need to remember to save the associated state when you save the city if you're delegating flag= , though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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