【问题标题】:Rails 3. How to add custom attributes to a select menu?Rails 3. 如何在选择菜单中添加自定义属性?
【发布时间】:2011-10-13 23:00:18
【问题描述】:

我有一张发票。

Invoice 包含 LineItems(属于 Items)。

在发票中,有一个用于选择行项目的下拉菜单。我需要添加两个自定义属性:data-quantitydata-price。 (HTML5)

我尝试按照这篇文章进行操作:http://www.redguava.com.au/2011/03/rails-3-select-list-items-with-custom-attributes/ 但它不适用于嵌套模型属性。

应用程序助手

def options_from_collection_for_select_with_attributes(collection, value_method, text_method, attr_name, attr_field, selected = nil)
  options = collection.map do |element|
    [element.send(text_method), element.send(value_method), attr_name => element.send(attr_field)]
  end
  selected, disabled = extract_selected_and_disabled(selected)
  select_deselect = {}
  select_deselect[:selected] = extract_values_from_collection(collection, value_method, selected)
  select_deselect[:disabled] = extract_values_from_collection(collection, value_method, disabled)

  options_for_select(options, select_deselect)
end

_line_item_fields.html.erb

Product: 
<%= f.select(:item_id, options_from_collection_for_select_with_attributes(@items, :id, :name, 'data-quantity', :quantity), {:prompt => 'Select'}, {:class=>'product'}) %>

我收到错误:#Item:0x007f53380eb2 的未定义方法“数量”

应用程序助手中的方法很可能运行良好,但问题是 LineItems 属于 Item。 LineItems 有数量属性,但项目没有数量属性。

从错误中可以看出,它正在查看 Item,但我确实应该引用 LineItem。

【问题讨论】:

  • 你能告诉我们你到目前为止尝试过的代码吗?
  • 感谢布兰登审查我的问题 :) 问题已更新。

标签: ruby ruby-on-rails-3 forms


【解决方案1】:

在这里找到答案:ruby on rails f.select options with custom attributes

Anatortoise House的答案

效果很好,无需在应用程序控制器中添加方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 2012-10-27
    • 2011-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多