【问题标题】:Rails simple constants and select optionsRails 简单常量和选择选项
【发布时间】:2011-03-30 09:10:29
【问题描述】:

我的模型 Inquire.rb 中有一个名为“subjects”的简单常量,我想知道是否有一种简单的方法可以使用 Ruby 数组中的位置,而不是使用 id 或更复杂的方法从它中生成哈希数组。

我可以这样做吗?

即而不是 to_s 就像它目前对选择中的值所做的那样,我想要一个整数来指示问题在数组中的位置。在这种情况下为 1-5。

谢谢

  SUBJECTS = [ "I have a query about my booking", 
               "I can't find my confirmation email", 
               "I have feedback about a location",
               "I have feedback about your website", 
               "Other enquiry" ]

<%= f.collection_select :subject, Inquire::SUBJECTS, :to_s, :titleize, {:prompt => true} %>

【问题讨论】:

  • 顺便说一句,在 config/ 中放入一个 yaml 文件并使用 YAML::load_file 加载是一件好事。

标签: ruby-on-rails ruby arrays forms


【解决方案1】:

您只需要一个小帮手为您工作。就像这个内置助手一样 - http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html

module form_collection_helper
  def options_with_index_for_select(items)
      html = ''
      items.each_with_index { |item, i|  html << "<option value='#{i}'>#{item.titleize}</option>" }
      return html
  end
end

在你的代码中只会:

<%= f.select :subject, options_with_index_for_select(Inquire::SUBJECTS), {:prompt => true} %>

【讨论】:

    【解决方案2】:

    或者,您可以使用通过 Enumerable 提供给您的 enum_with_index 方法。

    <%= f.select :name, Inquire::SUBJECTS.enum_with_index.collect { |s, i| [s.titleize, i] }, {:prompt=>true} %>
    

    【讨论】:

      【解决方案3】:

      你可以这样做

      <%= select(:inquire, :subject_id, 
            Inquire::SUBJECTS.collect {|x| [x, Inquire::SUBJECTS.index(x) + 1] }) 
      %>    
      

      这会产生以下 HTML

      <select id="inquire_subject_id" name="inquire[subject_id]">
        <option value="1">I have a query about my booking</option> 
        <option value="2">I can't find my confirmation email</option> 
        <option value="3">I have feedback about a location</option> 
        <option value="4">I have feedback about your website</option> 
        <option value="5">Other enquiry</option>
      </select> 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 1970-01-01
        • 2016-04-20
        相关资源
        最近更新 更多