2016-04-21 227 views
0
if @challenge.name == 'foo' 
    @challenge.category = 'habit' 
    @challenge.days_challenged = 21 
    @challenge.why = 'bar' 
else 

:days_challenged & :why正确的_form为foo被设置但不:category默认对象属性不默认为HTML

<div class="challenge-category"> 
    <input class="date-format-switcher" type="radio" value="goal" name="challenge[category]" id="challenge_category_goal"> 
    <label for="challenge_category_goal">Goal</label> 

    <input class="date-format-switcher" type="radio" value="habit" name="challenge[category]" id="challenge_category_habit"> 
    <label for="challenge_category_habit">Habit</label> 
    </div> 
    <%= f.number_field :days_challenged, class: 'day-challenge' %> 
    <%= f.text_area :why %> 
+0

快,让你的控制器的方法,并查看完整的代码 – Ilya

回答

1

我假设你有目的地为你的单选按钮定制编码。所选择的单选按钮应具备的属性“选中”,即

<input class="date-format-switcher" type="radio" value="habit" 
    name="challenge[category]" id="challenge_category_habit" checked /> 

动态设置:

<%= f.radio_button :category, 'goal', class: 'date-format-switcher' %> 
<%= f.radio_button :category, 'habit', class: 'date-format-switcher' %> 
+0

这使得它始终默认为“习惯” 。有时,特色挑战是“目标”,这意味着需要检查 –

+0

我知道。您需要以编程方式将其设置为检查单选按钮的值是否匹配“@ challenge.category”。 Rails有一个助手'f.radio_button',它可以像其他表单字段一样执行此操作。 – GoGoCarl

+0

请参阅上面的编辑。这基本上会产生相同的HTML,但让我们Rails为您处理表单构建。 – GoGoCarl