Home > Software engineering >  How do I use class_name to link two specific columns
How do I use class_name to link two specific columns

Time:05-05

I have a model called Company, this model is used for both companies and clients, I know this is not the best approach for companies/clients but the software I'm working on was built that way and to change that, it would take months of job.

class Company < ActiveRecord::Base
  has_many :companies
  belongs_to :company
  has_many :orders, dependent: :destroy
end

My other model is Orders, where the companies are linked by the company_id column and the customers by the customer_id column, that is, an order is linked to a company and a customer of that company.

class Order < ActiveRecord::Base
  belongs_to :company
end

Currently I created a method to get the customer but I would like to call a has_one to get the customer from the order, but I am not able to point the customer_id column of the order to the company id column using the rails class_name.

If anyone can help me in this endeavor I would be very grateful.

CodePudding user response:

If I understand your question correctly (in the first para you mentioned clients and in the second you are saying customers so I am assuming clients == customers and customer is also a Company object) you are trying to do this:

class Order < ActiveRecord::Base
  belongs_to :company

  has_one :customer, class_name: 'Company'
end

which seems incorrect as it should be belongs_to:

class Order < ActiveRecord::Base
  belongs_to :company
  belongs_to :customer, class_name: 'Company'
end

This should work but you can also specify foreign_key:

belongs_to :customer, class_name: 'Company', foreign_key: :customer_id

From the docs: https://api.rubyonrails.org/v7.0.2.4/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_one

has_one specifies a one-to-one association with another class. This method should only be used if the other class contains the foreign key. If the current class contains the foreign key, then you should use belongs_to instead.

  • Related