Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Calling a relation in after_initialize disables includes(:relation) functionality

#6733

When a relation is triggered in an after_initialize block the includes statement will not do its magic and falls back to separate requests. A reproduction scenario using Rails 3.0.7 on Ubuntu:

rails new after_initialize
cd after_initialize
rails g scaffold Post name:string body:text
rails g scaffold Comment email:string body:text post_id:integer
rake db:migrate

class Comment < ActiveRecord::Base
  belongs_to :post
end
class Post < ActiveRecord::Base
  has_many :comments
end

rails c

p1 = Post.create(:name => 'Post 1')
p2 = Post.create :name => 'Post 2'
p1.comments << p1.comments.create(:body => 'Comment 1')
p2.comments << p2.comments.create(:body => 'Comment 2')
Comment.includes(:post).map{|c| c.post.name} #=>  Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE ("posts"."id" IN (1,2))

Now the models with after initialize:

class Comment < ActiveRecord::Base
  belongs_to :post

  after_initialize do
    self.body = post.try(:name)
  end
end
class Post < ActiveRecord::Base
  has_many :comments
end

And in the console:

Comment.includes(:post).map{|c| c.post.name} #=>
  Post Load (0.1ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = 1 LIMIT 1
  Post Load (0.1ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = 1 LIMIT 1
  Post Load (0.1ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = 2 LIMIT 1

When the relation is not triggered in after_initialize, aka:

class Comment < ActiveRecord::Base
  belongs_to :post

  after_initialize do
    self.body = 'I am new'
  end
end
class Post < ActiveRecord::Base
  has_many :comments
end

Everything is ok. This can lead to performance drops.

Reported by bterkuile · April 20th, 2011 @ 06:41 PM

State: new
Milestone: none
Assigned to: nobody
Importance: none

Activity

No comments yet.