【问题标题】:Default object attribute not defaulting for HTML默认对象属性不是 HTML 的默认值
【发布时间】:2016-08-15 07:40:45
【问题描述】:
if @challenge.name == 'foo'
  @challenge.category = 'habit'
  @challenge.days_challenged = 21
  @challenge.why = 'bar'
else

:days_challenged & :why 正确设置在 foo 的 _form 中,但不是 :category

  <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 %>

【问题讨论】:

  • 请展示您的控制器方法并查看完整代码

标签: html ruby-on-rails ruby attributes radio-button


【解决方案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' %>

【讨论】:

  • 这使它始终默认为“习惯”。有时特色挑战是一个“目标”,这意味着需要检查
  • 我知道。如果单选按钮的值与@challenge.category 匹配,您需要以编程方式将其设置为检查。 Rails 有一个助手 f.radio_button 可以像其他表单字段一样执行此操作。
  • 见上面的编辑。这基本上会产生相同的 HTML,但让 Rails 为您处理表单构建。
猜你喜欢
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 2017-05-17
  • 2016-03-17
  • 1970-01-01
  • 2012-12-15
  • 2016-02-11
  • 2023-03-18
相关资源
最近更新 更多