I’m having problems with the select tag in my view.
First of all I’m using Rails 3.1.1 and Ruby 1.9.2 p290
The model is a Consumable which has a name, supplier, reorder number, type and associated printer models that it is compatible with.
The field that isn’t validating correctly is type which is fed values from an array in the Consumable model and the validation should be against inclusion of one of the elements of the array.
In the model, I define the field’s validation like so
TYPES = [ "REM", "REM-HICAP", "OEM", "OEM-HICAP" ]
validates :type, inclusion: TYPES
In the view (form partial for Consumable) I’ve created the select tag thusly
<div class="field">
<%= f.label "Type" %><br />
<%= f.select :type, Consumable::TYPES, prompt: 'Select a type...',
:selected => params[:type] %>
</div>
The drop-down box is creating well-formed HTML which looks like this
<div class="field">
<label for="consumable_Type">Type</label><br />
<select id="consumable_type" name="consumable[type]">
<option value="">Select a type...</option>
<option value="REM">REM</option>
<option value="REM-HICAP">REM-HICAP</option>
<option value="OEM">OEM</option>
<option value="OEM-HICAP">OEM-HICAP</option>
</select>
</div>
When I post the form this is the debug information
---
utf8: ?
_method: put
authenticity_token: nZZ9MastYswVCDrvAbgVLTUWqSRZLVrvRLmxOqPYk7I=
consumable:
description: Black Toner
supplier_id: '1'
reorder_no: '123456'
type: OEM
printer_model_ids:
- '1'
- '3'
commit: Update Consumable
action: update
controller: consumables
id: '1'
As is evident by the debug info, type is set correctly with a value from the select box (a string) and type in the model is a string. The form instead shows the validation error “Type is not included in the list” and if I remove the validation the database shows a nil value for the type field.
At what point is the validation applied to the form, does the controller trigger it by attempting to save the object?
I have used the same method of validating a drop-down box in the depot application in Agile Web Development with Rails 4th Edition with essentially the same code but a different name for the array and it works correctly.
I have just tested the same validation in the depot application and it works on this same workstation, so I would count out setup inconsistencies.
Thanks
I finally discovered my error:
Typeis protected in Rails and changing my variable name toKindmake it work correctly.