I need to create a form in my rails3 application that, when saved, will validate the fields and then submit them. I need a row for each field essentially.
The reason for this is that each ‘user’ has multiple attributes. For example:
- User-Password
- Expiration
- Access-Group
Have tried a nested form but that doesn’t really work for me.
In my console, this works pretty well for me:
user = Array.new
user << {:username => "jenny", :attribute_name => "User-Password", :value => "123"}
user << {:username => "jenny", :attribute_name => "Expiration", :value => "123"}
user << {:username => "jenny", :attribute_name => "Access-Group", :value => "123"}
User.create(user)
That inserts a number of rows, each with the same username but different attribute names and values. Perfect.
My problem is, how do I do this using a single form?? Initially I had a parent model and a nested form but I can’t figure it out.
This should actually be pretty straightforward nested form. Let us assume
and an
Attributehas anattribute_name, avalueand auser_id.Then your form, using haml, simple_form and cocoon would look like
and you add a partial called
_attribute_fields.html.hamlIf the attributes are fixed, you could easily change the input for
attribute_nametoIf you want to read more about different types of nested forms, I have written a blogpost about it in greater detail.
[EDIT] Adding server-side validation to
Attributemodel:Inside class
Attributeyou need to add:Note that the method
is_a_valid_date?does not exist, this is just to provide a small example. In this validation method you would then add all the possible attribute-value combinations with their validation.Hope this helps.