Saturday, 31 August 2013

Rails Filter Out Deleted Records in Association

Rails Filter Out Deleted Records in Association

My rails app needs to do a 'soft' delete of certain records so they are
inactivated without actually being removed from the DB. Currently I have
it implemented with an "is_deleted" flag.
My question is whether there's a best practice for handling associations
involving this model. For example:
class Foo
attr_accessible :is_deleted
scope :active, -> { where(is_deleted:false) }
belongs_to :bar
end
class Bar
has_many :foos
end
I'm trying to figure out how to set up the Bar model, knowing that it
usually deals only with 'active' foos.
I have come up with a couple ideas, and would like to know if there are
any pros/cons for using one over the other.
Use a "condition" qualifier on the has_many declaration to filter out
deleted items.
Create a "active_foos" method on Bar to return only the undeleted items.
Just use the "acts_as_paranoid" gem. It feels a little heavyweight for
what I need, but perhaps it's easiest.

No comments:

Post a Comment