How to preset _form for recognized objects?

User can enter custom :action or select recognized :action :

 <%= f.text_field :action %> Or choose a featured challenge: <%= f.collection_radio_buttons :action, [['Run a Mile','Run a Mile'], ['Drink 16oz of Water','Drink 16oz of Water'], ['Take a Picture','Take a Picture'], ['1 Drink Max','1 Drink Max'], ['See Eiffel Tower','See Eiffel Tower'], ['Write a Book','Write a Book'], ['Skydive','Skydive'], ['Start a Business','Start a Business'], ['No Snooze','No Snooze'], ['Visit All 50 States','Visit All 50 States'], ['Talk to a Stranger','Talk to a Stranger'], ['Try a New Recipe','Try a New Recipe'], ['Media-fast','Media-fast']], :first, :last %> 

If the user selects the :action flag, the new / _form calls are pre-populated with the selected :action , but now I would like to go to the next level with your help!

 <%= form_for(@challenge) do |f| %> Challenge: <%= f.text_field :action %> Do On: <%= f.collection_check_boxes :committed %> Do For: <%= f.number_field :days_challenged %> <% end %> 

How can I pre-populate other attributes of a recognized call, such as "Do For" or "Do On"?

For example, if the user selected the attribute :action : 'Run a Mile , I would have pre-filled the Run a Mile , Mon, Wed, Fri , 30 Days form.

+7
object ruby ruby-on-rails forms attributes
source share
1 answer

You can use simple_form with reform . Reform will give you a form object where you can override the methods that will fill your form.

Here is an example with water (you will need to adapt it to your case):

 class ChallengeForm < Reform::Form property :action property :committed property :days_challenged model :challenge def commited super || action_to_commited_hash[model.action] end def days_challenged super || action_to_days_challenged_hash[model.action] end def action_to_days_challenged_hash { 'Run a Mile' => 30, 'Take a Picture' => 12 } end def action_to_commited_hash { 'Run a Mile' => ['Mon', 'Wed', 'Fri'], 'Take a Picture' => ['Tu', 'Thu'] } end end 

super in the above methods will delegate model . Note that you override getter methods, and this does not affect setters (you can also override setters if you want to write form data before writing it).

In your template instead

 form_for @challenge 

you will have:

 simple_form_for @form 

This is a super generic form library for Rails, and I can't imagine not using it myself!

+2
source share

All Articles