Associations on parent record not set when accessed via nested reject_if

I’m using accepts_nested_attributes_for with a reject_if and I’m trying to access a relationship from the parent that’s holding the nested attributes from inside the reject_if function. When I do this however, it seems that a belongs_to relationship returns nil. I’ve got a quick example here:

class Car
   belongs_to :manufacturer
   accepts_nested_attributes_for :wheels, reject_if :reject_if_blank_and_ford

   def reject_if_blank_and_ford(attributes)
      return false if attributes[:wheel_size].blank? and self.manufacturer.make == "Ford"

The issue is that when doing:

manufacturer = Manufacturer.find_by_make("Ford")[:car])

in the reject_if, self.manufacturer is nil. If I try it out with a before_validation:

before_validation do

This works. It leads me to believe that the relationship to manufacturer is instantiated/setup AFTER the reject_if - is there any way to access this relationship in the reject_if block?

I am pretty sure that the only thing the reject_if proc has available to it at the moment it is evaluated are the params collected from the form. If you were passing in the parent ID, you might be able to hydrate it with ModelName.find, but you would also not have the child as an object inside that proc. I stand to be corrected, but that’s the way I have treated these values inside my more custom reject_if logic.


Thanks Walter. I imagine that it’s all based on the ordering that the attributes are established looking at the stack trace. I even wonder if its based on the order the attributes appear - for example manufacturer relationship is setup after the wheels attributes. I’ll just have to deal with it.