Saving association in callback method Rails 3.1 #1594

Closed
releu opened this Issue Jun 9, 2011 · 2 comments

Comments

Projects
None yet
2 participants
@releu
Contributor

releu commented Jun 9, 2011

Hi!

Trouble:

class Account < ActiveRecord::Base
  belongs_to :user

  before_create do
    build_user
  end

end
Account.create # => 
INSERT INTO "accounts" ("created_at", "updated_at", "user_id") VALUES (?, ?, ?)  [["created_at", Thu, 09 Jun 2011 04:54:59 UTC +00:00], ["updated_at", Thu, 09 Jun 2011 04:54:59 UTC +00:00], ["user_id", nil]]
 => #<Account id: 1, user_id: nil, created_at: "2011-06-09 04:54:59", updated_at: "2011-06-09 04:54:59">

( Only account created )

class Account < ActiveRecord::Base
  belongs_to :user

  before_validation :on => :create do
    build_user
  end

end

Account.create # => 
INSERT INTO "users" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Thu, 09 Jun 2011 04:55:27 UTC +00:00], ["name", nil], ["updated_at", Thu, 09 Jun 2011 04:55:27 UTC +00:00]]
  SQL (0.3ms)  INSERT INTO "accounts" ("created_at", "updated_at", "user_id") VALUES (?, ?, ?)  [["created_at", Thu, 09 Jun 2011 04:55:27 UTC +00:00], ["updated_at", Thu, 09 Jun 2011 04:55:27 UTC +00:00], ["user_id", 1]]
 => #<Account id: 2, user_id: 1, created_at: "2011-06-09 04:55:27", updated_at: "2011-06-09 04:55:27">

( Account and user created )

Is it ok?

@pixeltrix

This comment has been minimized.

Show comment
Hide comment
@pixeltrix

pixeltrix Jun 9, 2011

Member

This is to be expected - the save_belongs_to_association in ActiveRecord::AutosaveAssociation is called in a before_save callback itself. The callbacks are executed in the order they are defined so if you move your before_save before the association declaration it should work.

Member

pixeltrix commented Jun 9, 2011

This is to be expected - the save_belongs_to_association in ActiveRecord::AutosaveAssociation is called in a before_save callback itself. The callbacks are executed in the order they are defined so if you move your before_save before the association declaration it should work.

@releu

This comment has been minimized.

Show comment
Hide comment
@releu

releu Jun 9, 2011

Contributor

oh. thanks

Contributor

releu commented Jun 9, 2011

oh. thanks

@releu releu closed this Jun 9, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment