accepts_nested_attributes_for 3.0.5 :reject_if still have gotchas


Nested forms are nasty, but many times, a necessary evil 🙂

Rails tackled it since version 2.3x, when added the ActiveRecord method accepts_nested_attributes_for, main ref here. For its complexity, I believe, it is still hard to master it, and still bugs may happen; this was my lesson.

Ryan Bates, (a ruby hero) has made some screencasts from it, watch part1, part2. Soon after, he and some buds, made a gem for it, targeting Adding and Removing via JavaScript, without harassment. You can find on GitHub, along with the necessary doc.

So, using the gem or not, still there are things to cover over this methods params;

From what I could observe, :reject_if, does not work for ‘rejecting’ a existing record, i.e.: those that have ID. But, it is called for those too! – In this topic, (what may be a bug) is that, if the record gets rejected, it does not get updated (it does not go through it’s model’s validations either).

The solution I found was not using :reject_if,  instead, validating whatever I wanted on the nested Model in order to keep dry.

For this scenario, consider the following setup (rails v3.0.5)

class A < ActiveRecord::Base
 has_many :bs
 accepts_nested_attributes_for :bs,
                               :allow_destroy => true
                               #no use. :reject_if => :combo_elem_zero?

 # wont use this function at all
 def combo_elem_zero?( att )
  #att['_destroy'] = '1' # wont work here

  # only useful for new records
  if atribs['id'].blank? && att[:some_atrib].to_f < something_blah

class B < ActiveRecord::Base
 belongs_to :a

 validate :destruction_update # works both for create/update

 def destruction_update
  if self.some_atrib.to_f < something_blah


If on the other hand, you only need to check on the nested new records, :reject_if may do the job.


One thought on “accepts_nested_attributes_for 3.0.5 :reject_if still have gotchas

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s