开发者

One SQL Call for destroying records with property "a" or "b" in ActiveRecord?

I want to destroy all objects that have parent_type == 'Profile' or child_type == 'Profile', like this:

Relationship.destroy_all(:parent_type => "Pro开发者_JS百科file")
Relationship.destroy_all(:child_type => "Profile")

How do I combine that into one method and one sql call?

Went with something like this:

class Group < ActiveRecord::Base
  has_many :relationships

  after_destroy :destroy_relationships

  def destroy_relationships
    conditions = %Q|(`relationships`.parent_type IN ("#{self.class.name}","#{self.class.base_class.name}") AND `relationships`.parent_id = #{self.id}) OR (`relationships`.child_type IN ("#{self.class.name}","#{self.class.base_class.name}") AND `relationships`.child_id = #{self.id})|
    Relationship.delete_all(conditions)
  end
end


Use a SQL condition instead of a hash:

Relationship.destroy_all("(parent_type = 'Profile') OR (child_type = 'Profile')")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜