Question

I was unable to setup my tables using the id field as the primary_id (I mean they are there but they don't mean anything to the business). ie Both the sales and customer tables come from our Microsoft SQL database.

In the Sales table I have a field called 'customer_id' that matches the 'customer_id' (not the 'id' field) in the customers table. My 'customer_id' field datatype is set to integer but in the migrations I never specified whether they were keys. I only indexed them.

The sale belongs to the customer and the customer has many sales so I am trying to make the has_many and belongs_to association.

sale.rb

class Sale < ActiveRecord::Base

    belongs_to :customer, primary_key: "customer_id", foreign_key: "customer_id"

end

customer.rb

class Customer < ActiveRecord::Base

    has_many :sales


end

However when I get the rails console and try to test this I am unable to have the SQL search for the customer_id, only the id from the customers table is searched.

rails console

    2.0.0-p353 :001 > c = Customer.find_by_customer_id(400123)
  Customer Load (2.0ms)  SELECT "customers".* FROM "customers" 
WHERE "customers"."customer_id" = 400123 LIMIT 1
 => #<Customer id: 16271, customer_id: 400123, customer_name: "ABC", 
customer_street: "ABC", customer_suburb: "ABC", customer_state: "ABC",
customer_postcode: "ABC", dispatch_location_price_list: "ABC", customer_selling_price_list: 
"ABC", customer_status: "ABC", line_of_business_id: "ABC", line_of_business: "ABC", 
market_segment_id: "ABC", market_segment_name: "Other", customer_rep_id: 123, customer_rep_name: "ABC"

2.0.0-p353 :002 > c.sales
  Sale Load (7.1ms)  **SELECT "sales".* FROM "sales" 
WHERE "sales"."customer_id" = $1      [["customer_id", 16271]]**
 => #<ActiveRecord::Associations::CollectionProxy []> 

Specifically I just want the last bit to say [["customer_id', 400123]].

I know it is probably obvious but as I am still learning a lot of this stuff takes a bit to sink in (alot of cases I have answered my question just by asking it but not so tonight). Any suggestions would be greatly appreciated.

In my research I have found this in the API:

4.2.2.7 :primary_key

By convention, Rails assumes that the column used to hold the primary key of this model is id. You can override this and explicitly specify the primary key with the :primary_key option.

Which made me think I should be using the primary_key as the 'id' field isn't the field to be looked up using.

I also read this thread but I think it may be a little different than my situation.

Was it helpful?

Solution

Have you tried to add self.primary_key = :customer_id to the Customer model?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top