This project is archived and is in readonly mode.

#6733 new
bterkuile

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

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

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.

No comments found

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Pages