user1032752
user1032752

Reputation: 881

Rails use a method for an associations primary key

I have a model with a serialized value (using store_accessor) that contains an associated objects ID. For example:

class Foo < ActiveRecord::Base 
  store_accessor :settings, [:bar_id]

  belongs_to :bar, foreign_key: :bar_id, primary_key: :id
end

Foo.first.bar_id => 123
Foo.first.bar => nil 

I know there exists a Bar with an ID of 123 and I can see that the query is never even made - I'm assuming this is because Rails incorrectly thinks that bar_id is nil.

What am I doing wrong?

Rails 4.2.10

Update #1

Foo.find(1).bar_id
Foo Load (0.5ms)  SELECT  "foos".* FROM "foos" WHERE "foos"."id" = $1 LIMIT 1  [["id", 1]]
=> "123"

Foo.find(1).bar
Foo Load (0.5ms)  SELECT  "foos".* FROM "foos" WHERE "foos"."id" = $1 LIMIT 1  [["id", 1]]
=> nil

Bar.find Foo.find(1).bar_id
Foo Load (0.5ms)  SELECT  "foos".* FROM "foos" WHERE "foos"."id" = $1 LIMIT 1  [["id", 1]]
Bar Load (0.4ms)  SELECT  "bars".* FROM "bars" WHERE "bars"."id" = $1 LIMIT 1  [["id", 123]]
=> #<Bar id: 123>

Upvotes: 1

Views: 362

Answers (1)

Igbanam
Igbanam

Reputation: 6082

I believe this is because of how both attributes are stored in the model. If you reference how the belongs_to association is setup, it uses an attribute on the model. The store on a model defines a _read_store_attribute which is different from _read_attribute.

If these two are different, which they are, the belongs_to association on a model would not be setup.

In your case, it's looking for bar_id as an attribute in the model; not a virtual attribute.

Upvotes: 3

Related Questions