views:

103

answers:

1

Hey guys,

I was wondering how to go about form validation in rails. Specifically, here is what I'm trying to do:

The form lets the user select an item from a drop down menu, and then enter a number along with it. Using RJS, the record instantly shows up in a table below the form. Resetting the form with AJAX isn't a problem.

The issue is, I don't want the person to be able to select the same item from that drop down menu twice (in 1 day at least). Without using ajax, this isn't a problem (as I have a function for the select statement currently), but now that the page isn't reloading, I need a way to make sure people cant add the same item twice in one day.

That said, is there a way to use some javascript/ajax validation to make sure the same record hasn't been submitted during that day, before a duplicate can be created?

Thanks in advance!

Elliot

+1  A: 

With regards to form validations, for your special logic, you'll want to override #validate in your model. See the docs for ActiveRecord::Validations#validate.

Your best bet to "make sure people cant add the same item twice in one day" is to not present the user with options that they can't select. When your controller prepares data for the view have logic that filters out any options that the user shouldn't have (i.e. those they already selected that day). Or present them but disable them as options (so they are grayed out). If the user could select the same option twice in one request you'll want some JS to do client-side validation before a POST to the server.

Chris
Hey Chris, I'm using ajax, so the page isn't refreshing. Meaning the first time a record is added, the options should be different the second time. But the controller isn't accessed in between.
Elliot
The controller is accessed in between, it's just handling an ajax request. Your model should handle the validation with #validate. If validation fails your controller needs to send back an ajax response that updates the view with an error message. Otherwise have the controller send back a list of new options that you can update the user's selection with.
Chris