用户可以输入自定义:操作或选择特色:操作:
<%= 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 %>
如果用户选择了特色:动作,则新挑战/ _form会预先填充他选择的:动作,但现在我想在你的帮助下将其提升到新的水平!
<%= 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 %>
如何预先填充特色挑战的其他属性,例如“Do For”或“Do On”?
例如,如果用户选择了特色:动作:’运行一英里,那么我将预先填充表格,运行一英里,周一,周三,周五,30天.
解决方法
你可以使用simple_form进行改革.改革将为您提供表单对象,您可以在其中覆盖将填充表单的方法.
这是一个淡化的例子(你必须根据你的情况调整它):
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将委托给模型.请注意,您要覆盖getter方法,并且它不会影响setter(如果您想在编写表单数据之前更改表单数据,也可以覆盖setter).
在您的模板中,而不是
form_for @challenge
你将会有:
simple_form_for @form
它是Rails的一个超级常见的表单库,我无法想象自己不使用它!