M
M
Meridian3122014-05-06 12:04:59
Ruby on Rails
Meridian312, 2014-05-06 12:04:59

How to change the id of the current model instance for the has_one connection?

The documentation says for has_one
:primary_key
Specify the method that returns the primary key used for the association. By default this is id.
As I understand it, when a model uses this relationship, then the referenced table is searched for by primary_key, which by default is the id of this model and which in turn has a has_one relationship

class Model_A
  belongs_to model_b
end

class Model_B
  has_one model_a
end

therefore, the modeL_a attribute of an instance of the Model_B class will be searched as
SELECT "model_a".* 
FROM "model_a" WHERE "model_a"."model_b_id" = $1 
ORDER BY "model_a"."id" ASC LIMIT 1  

Is there any way to replace the insert <> in the query for the model containing the has_one relationship?
What is the essence of primary_key in has_one, if only as a redefinition of the name of the primary key of the field?
Is it possible to make subsequent links referencing Model_B via has_one :through also replace the <> insertion as needed?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question