rasmusrn
2009-Aug-21 14:46 UTC
AR: Association load after validations if build from within before callback?
Hi, I''m seeing some very odd behavior which I hope you can explain. If I build an object via a has_many association within a before_save/ before_create of a parent active record object, Rails attempts to load the association. This log snippet explain what I mean: Processing UsersController#create (for 127.0.0.1 at 2009-08-21 16:34:37) [POST] Parameters: {"user"=>{"name"=>"asdsad"}, "commit"=>"Create", "authenticity_token"=>"rqI1EgrWycqHqdUriCiqpIp8rvOa3siD/dwzHolCGMA="} User Create (0.4ms) INSERT INTO "users" ("name", "updated_at", "created_at") VALUES(''asdsad'', ''2009-08-21 14:34:37'', ''2009-08-21 14:34:37'') Post Load (0.1ms) SELECT * FROM "posts" WHERE ("posts".user_id NULL) Post Create (0.1ms) INSERT INTO "posts" ("updated_at", "title", "text", "user_id", "created_at") VALUES(''2009-08-21 14:34:37'', ''test'', NULL, 10, ''2009-08-21 14:34:37'') Redirected to http://localhost:3000/users/10 Completed in 14ms (DB: 1) | 302 Found [http://localhost/users] Here''s the test code: class User < ActiveRecord::Base has_many :posts def before_create posts.build :title => ''test'' end end If I move the posts.build out of the before_*, the association is not loaded. For instance: class UsersController < ApplicationController def create @user = User.new(params[:user]) @user.posts.build :title => ''test'' @user.save [...] end .. and .. class User < ActiveRecord::Base has_many :posts end ... yield this log output: Processing UsersController#create (for 127.0.0.1 at 2009-08-21 16:42:11) [POST] Parameters: {"user"=>{"name"=>"Donald Duck"}, "commit"=>"Create", "authenticity_token"=>"rqI1EgrWycqHqdUriCiqpIp8rvOa3siD/dwzHolCGMA="} User Create (0.4ms) INSERT INTO "users" ("name", "updated_at", "created_at") VALUES(''Donald Duck'', ''2009-08-21 14:42:11'', ''2009-08-21 14:42:11'') Post Create (0.1ms) INSERT INTO "posts" ("updated_at", "title", "text", "user_id", "created_at") VALUES(''2009-08-21 14:42:11'', ''test'', NULL, 13, ''2009-08-21 14:42:11'') Redirected to http://localhost:3000/users/13 Completed in 12ms (DB: 0) | 302 Found [http://localhost/users] The above is tested on a clean newly generated rails app with Rails 2.3.3. Is this intentional, and if so, why is the association loaded when the parent id is NULL? Thanks in advance. Rasmus Rønn Nielsen www.rrn.dk / www.virtualmanager.com