如何在rails3中使用data-attribute?

时间:2012-10-27 05:10:13

标签: ruby-on-rails-3 custom-data-attribute

我有一个html选择语法,如:

<select id="salary_structure_salary_structure_line_items_attributes_0_payhead_id" class="half" name="salary_structure[salary_structure_line_items_attributes][0][payhead_id]">
<option data-payhead="Earnings" value="2"> Basic </option>
<option data-payhead="Earnings" value="3"> Daily allowance </option>
<option data-payhead="Standard deductions" value="4"> Employee provident fund </option>
</select>

我如何在rails语法中完成这项工作?我应该在下面的代码中做些什么改变才能得到上述结果:

<%= select_tag "salary_structure[salary_structure_line_items_attributes][#{index}][payhead_id]", options_from_collection_for_select(@payheads, :id, :payhead_name, :selected => salary_structure_line_item.payhead_id ), :include_blank => true, :class => "half"%> 

我也希望在此代码中使用'selected'选项。

2 个答案:

答案 0 :(得分:2)

嘿,我认为使用选择

的集合中的选项会相当复杂

请参阅:http://www.redguava.com.au/2011/03/rails-3-select-list-items-with-custom-attributes/

答案 1 :(得分:1)

options_array = [
  ["Basic", 2, "data-payhead" => "Earnings"],
  ["Daily allowance", 3, "data-payhead" => "Earnings"],
  ["Standard deductions", 4, "data-payhead" => "Standard deductions"]
]

select_tag("salary_structure[salary_structure_line_items_attributes][0][payhead_id]", options_for_select(options_array, value), :class => "half")

在上面的代码中,在options_for_select方法中,请使用select box选项的值指定值。这将嵌入该选项的选定属性