Andy Fiedler
Andy Fiedler

Reputation: 513

How can I prevent adding/deleting records to an Active Record association based on another field?

Is there anyway to override the behavior of all of the writable ActiveRecord association methods? For example, I have a model called "Request" like this:

class Request < ActiveRecord::Base
   has_many :line_items
end

The Request model has a field called "status". If status is not "DRAFT", I want all of the writable ActiveRecord association methods for the line_items relations to throw an exception. I know I can override them indivdually, like this:

class Request < ActiveRecord::Base
   has_many :line_items

   def line_items=(args)
      if status != 'DRAFT'
         raise Exception.new "cannot edit a non-draft request"
      else
         write_attribute :line_items, args
      end
   end
end

However, there are a lot of methods that ActiveRecord creates for these associations (see "Auto-generated methods" on http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html).

Thanks for any help.

Upvotes: 0

Views: 142

Answers (1)

Amol Pujari
Amol Pujari

Reputation: 2349

if some objects are not been accepted by your rails code, first you would look at that object class itself and not any other associated class, unless you really track that ok, these rules for line_items are actually coded in request model. Its better LineItem to know why its objects being rejected, rather than Request to know it.

Then, you many not want absolutely all request associations to follow the same rule.

And so, I propose this,

class LineItem < ActiveRecord::Base
  belongs_to :request
  before_save :raise_if_draft_request
  def raise_if_draft_request
    raise Exception.new "cannot edit a non-draft request" if self.request.status=='DRAFT'
  end
end

Upvotes: 1

Related Questions