A user can input a custom :action
or choose a featured :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 a user chooses a featured :action
the new challenges/_form is pre-populated with his chosen :action
, but now I'd like to take it 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 the other attributes of a featured challenge like, "Do For" or "Do On"?
For example if a user chose the featured :action
: 'Run a Mile
then I would pre-populate the form with Run a Mile
, Mon, Wed, Fri
, 30 Days
.
答案 0 :(得分:2)
您可以将simple_form
与reform
一起使用。改革将为您提供表单对象,您可以在其中覆盖将填充表单的方法。
这是一个淡化的例子(你必须根据你的情况进行调整):
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
将委托给model
。请注意,您要覆盖getter
方法,并且它不会影响setters
(如果您想在编写表单数据之前更改表单数据,也可以覆盖setter)。
在您的模板中,而不是
form_for @challenge
你将拥有:
simple_form_for @form
它是Rails的超级常用表单库,我无法想象自己不使用它!