Tuesday, August 11, 2009

acts_as_paranoid gotcha

When eager-loading paranoid associations, beware that acts_as_paranoid's default behavior is to load ALL records, deleted or not. For example,

class User < ActiveRecord::Base
  has_many :blogs
end

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  acts_as_paranoid
end

# this will include deleted posts too!
@user.blogs.all(:include => :posts)

To only load associations that are not deleted, specify in your association conditions:

class Blog < ActiveRecord::Base
  has_many :posts, :conditions => "deleted_at IS NULL"
end

No comments: