Give your :reject_if some sugar

Tired of writing stuff like this?

accepts_nested_attributes_for :photo,
                              :allow_destroy => true,
                              :reject_if => proc { |attrs| reject = %w(title picture).all?{|a| attrs[a].blank?} }

Throw this snippet into init.rb into a new plugin folder (I called it reject_if_missing).

module RejectIfMissing
  def missing_attrs?(*required_attrs)
    Proc.new { |attrs| required_attrs.all?{|a| attrs[a].blank?} }
  end
end

ActiveRecord::Base.send(:extend, RejectIfMissing)

Now you can do this instead.

accepts_nested_attributes_for :photo,
                              :allow_destroy  => true,
                              :reject_if      => missing_attrs?('title', 'picture')

Leave a Reply