Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom association for Rails models

I'm trying to define a relation between 2 models Customer and CustomerProduct, linking customer.custom_id on customerproduct.customer_id so that mycustomer.customer_products.create() ends up with customerproduct.customer_id = customer.custom_id instead of customer.id.

This is my Customer model:

class Customer < ActiveRecord::Base
  belongs_to :organisation
  has_many :customer_products, foreign_key: 'customer_id'
end

And my CustomerProduct model:

class CustomerProduct < ActiveRecord::Base
  belongs_to :customer
end

I'm not sure how to define the custom_id bit - I tried adding it as a foreign key in belongs_to :customer but this doesn't seem to do anything - Rails still takes customer.id.

Thanks in advance!

like image 369
Davor Avatar asked Dec 01 '25 16:12

Davor


1 Answers

Let's just say the answer was quite obvious so I must have been blind!

has_many :customer_products, primary_key: 'custom_id', foreign_key: 'customer_id'
like image 167
Davor Avatar answered Dec 04 '25 06:12

Davor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!