stevenspiel
stevenspiel

Reputation: 5999

Rails update foreign key with id of association

I have an association with an id, but the foreign key is not being set.

Some setup:

Foo has_many :bars
Bar belongs_to :foo

foo = Foo.new.save
bar = Bar.new(foo: foo)

The output:

bar.foo = foo
bar.foo.id = 1
bar.foo_id = nil # Why is this nil!?

Other than assigning bar.foo_id = 1, is there a method to update the associated foreign key, so bar.foo_id == 1 without saving?

There must be some kind of #update_foreign_keys, or #update_associations method, right?

I'm running Rails 4.2 with Ruby 2.1.2

Upvotes: 1

Views: 2082

Answers (1)

Jorge de los Santos
Jorge de los Santos

Reputation: 4633

The id is set by the database, not by rails, that's why is empty.

You need to save each object in order to get an id.

You can save the object in a transaction in order to get one in case you need it to perform any magic.

And about the code:

bar.foo = foo
bar.foo.id = 1            <- This retrieves the ruby#object_id
bar.foo_id = nil          <- This retrieves the database#id

That's why the second one is nil.

Upvotes: 1

Related Questions