Davor
Davor

Reputation: 1237

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!

Upvotes: 3

Views: 702

Answers (1)

Davor
Davor

Reputation: 1237

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'

Upvotes: 2

Related Questions