Rails validation error with select tags
Ive just set up some basic models using scaffold with Rails, i've edited the views so that im taking input from a textfield and a selection box. Here are some code snippets:
form_for(@town) do |f|
f.text_field :name
.
.
f.select :county_id, @counties.map{|c| [c.name, c.id]}
.
.
end
Using the validation method "validates_presence_of" for the textfield and no validation on the selection box I can enter values and successfully write to the database. When I try to test validation by not entering anything into the textfield, I get a NoMethodError with the following message
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.map
Note: there is no validation on the selection box
If I comment out the "validat开发者_运维百科e_presence_of" line I can write blank data to the db with no problems. However if I write validate code for the textfield and it cause the entire form object becomes nil apparently...is Rails' validation causing this?
Any thoughts/comments are greatly appreciated. Im using Rails 2.3.4
You haven't posted the stack trace, but I'm assuming the error is occurring when you call map
on @counties
.
You probably have two actions in your controller handling the form. One (either new
or edit
) shows the form and responds to get requests. The other (either create
or update
) does the creation or update of the model. This responds to post or put requests and will either redirect if successful or render the new
or edit
action when there are validation errors (if save
fails).
I expect your new
or edit
action has some code that assigns to @counties
. Your create
or update
action will also need to assign @counties
when save
fails so that it is available in the view.
In your new method, how are you creating @counties and what are you putting into that variable? Also, without seeing your new and create methods, it is somewhat hard to tell exactly what is going on. Are you getting this error when you try to access the page above or when you try and submit the form?
For what it's worth, you do not have validations on form objects, you have validations on model attributes. As such, you need to check the params that are being passed to your controller when you submit your form and ensure that you are getting what you expect. Then match those params to the various validates_ methods that you have in your model.
Debugging this is a simple case of first checking to ensure that your form and the data in it are correct and then that the params being sent to your controller are correct. Remember, you need to check both the key and the value.
Also, use script/console and try creating a few model objects using the data that you are expecting your form to send and see what happens.
See this question
Your problem is symptom of the same thing.
精彩评论