Possible to alias a belongs_to association in Rails?

at. picture at. · Jan 31, 2014 · Viewed 33.4k times · Source

I have a model with a belongs_to association:

class Car < ActiveRecord::Base
  belongs_to :vendor
end

So I can call car.vendor. But I also want to call car.company! So, I have the following:

class Car < ActiveRecord::Base
  belongs_to :vendor
  def company
    vendor
  end
end

but that doesn't solve the assignment situation car.company = 'ford', so I need to create another method for that. Is there a simple alias mechanism I can use for associations? Can I just use alias_method :company, :vendor and alias_method :company=, :vendor=?

Answer

pramod picture pramod · Jan 31, 2014

No it doesn't look for company_id for instance change your code as follows

In Rails3

class Car < ActiveRecord::Base
   belongs_to :vendor
   belongs_to :company, :class_name => :Vendor,:foreign_key => "vendor_id"
end

In Rails4

We can use alias attribute.

alias_attribute :company, :vendor