Rails 3.1 Nested Models

Hi guys,
I’m having a bit of a frustrating problem – I’ve got two models,
drivers and incidents. A driver can have many incidents and the form for
drivers includes a section for incidents (using fields_for). However, a
driver can also have zero incidents, so on the form there is a radio
button that shows/hides the incidents stuff. My problem is that I need
it to validate ONLY if the user has specified that radio button to true.
Here’s what I have set up:

driver.rb

has_many :incidents
accepts_nested_attributes_for :incidents, :allow_destroy => true

incident.rb

belongs_to :driver
bunch of validations

drivers_controller.rb (create)

params_hash = params[:driver]
unless params[:driver][:suspended_or_revoked] == “true”
params_hash.delete(‘incidents_attributes’)
@driver = Driver.new(params_hash)
else
@driver = Driver.new(params[:driver])
end

What I try to do is delete the incidents_attributes hash from the driver
params, assuming that since it’s not submitting any data to incidents,
it won’t go through the validations. However, it DOES go through the
validations, regardless of if I have that hash in there or not.

Basically, I’m trying to bypass the validations for incidents (and
prevent creating incident objects) if the driver selected “no” to the
[:driver][:suspended_or_revoked] question. I know that the condition in
the controller is working, as I’ve done some logger.debug stuff to make
sure it’s going to the right blocks.

From what I’ve researched, this is the standard way to do this, but it
doesn’t seem to work (at least in Rails 3.1) … can somebody point me
in the right direction here?

Any and all help is appreciated :slight_smile:

Thanks,

  • Jeff

Hi Jeff

Maybe you should try reading this

and check carefully the “reject if” option

Hope this can help you

BAH! I found my problem after looking at my controller code with a fresh
mind. After the @driver.save, there was also a @driver.valid? that was
determining the type of json response. Ugh… so it was completely
unrelated. Well, at least I know all about how nested models work now :slight_smile:

Thanks,

  • Jeff