如何使用f.select获取静态哈希值

How to use f.select for static hash value?

本文关键字:静态 哈希值 获取 select 何使用      更新时间:2023-09-26

如何使用f.select标签来收集静态哈希值

class ReceiptPrinter
         RECEIPT_PRINTER_TYPES ={
            0=> "Normal",
            1=> "Dot Matrix",
            2=> "Thermal",
          }
        def initialize(options={})
                @receipt_printer_type=options[:receipt_printer_type] || DEFAULT_VALUES[:ReceiptPrinterType]
                @receipt_printer_header_height=options[:receipt_printer_header_height]|| DEFAULT_VALUES[:ReceiptPrinterHeaderHeight]
                @receipt_printer_header_type=options[:receipt_printer_header_type]|| DEFAULT_VALUES[:ReceiptPrinterHeaderType]
                @receipt_printer_template=options[:receipt_printer_template]|| DEFAULT_VALUES[:ReceiptPrinterTemplate]
                # define_methods()
        end
 end

在我的视图页,我使用select选项

<% form_for @receipt_printer, :url => { :action => "fees_receipt_settings" } do |f| %>
    <%= f.select("receipt_printer_template", @settings.map{| item| [item[0],item[1].to_i]},{},{:onchange => "set_template(this.value)"} ) %>
<% end %>

我得到错误的参数数错误

您可以尝试使用rails的options_for_select

<%= f.select :receipt_printer_template",options_for_select(@settings.map{ |item| [item[0], item[1]],{},{:onchange => "set_template(this.value)"} ) %>

这里是参考

回答

由于@settings只是一个简单的散列,您不必使用mapselect表单帮助器应该如下所示:

<%= f.select :receipt_printer_template, @settings, {}, {onchange: "set_template(this.value)"} %>

提出重构

如果你坚持使用map,我建议稍微重构一下代码,以防止你的视图被应用程序逻辑淹没,比如:

# app/helpers/receipt_helper.rb
def settings_for_select
  @settings.map{ |item| [item[0],item[1].to_i] }
end
# your form view
<%= f.select :receipt_printer_template, settings_for_select, {}, {onchange: "set_template(this.value)"} %>

应该已经有一点帮助了,还要注意new哈希语法的使用,它提供了一个更干净的API。