I have a model with a lot of fields where many of them are closely related.
Say I have the model: Fruit with attrs: fruit_type: ['apple', 'banana'], fruit_color: ['red', 'green', 'yellow'], is_rotten: ['true', 'false'].
Now I want to create some super user friendly create/edit forms for these models, where users can edit the attributes. Rails is great for this:
creating a form like:
= form_for @fruit do |f|
= f.select :fruit_type, options_for_select(['apple', 'banana'])
= f.select :fruit_color, options_for_select(['red', 'green', 'yellow'])
= f.check_box :is_rotten
= f.submit "save!"
Will give you all the great benefits of rails automatically rendering which value the attribute is currently taking etc. etc. with very limited amount of code.
Now. In reality, if this is gonna be super user-friendly and fast to use, it would be much more meaningful to combine some of these fields, so the user would only have to select one item from a combined list, which would then generate the right data on the model:
= form_for @fruit do |f|
= f.select :fruit_color_and_fruit_type, options_for_select(['Yellow apple', 'Red apple', 'Green apple', 'Yellow banana'])
= f.check_box :is_rotten
= f.submit "save!"
This however is of cause not supported straight out of rails. So, what pattern(s) could I use to make this play nice with rails' standard ways of doing things (strong params, pre-setting the value in the form, attribute mass assignment etc. etc.), so I don't have to hack and hardcode everything everywhere?
Aucun commentaire:
Enregistrer un commentaire