Skip to content

Loading…

Saving association in callback method Rails 3.1 #1594

Closed
releu opened this Issue · 2 comments

2 participants

@releu

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
Ruby on Rails 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.

@releu

oh. thanks

@releu releu closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.