【问题标题】:rails form for model select box with 1-dimensional data带有一维数据的模型选择框的导轨形式
【发布时间】:2015-11-23 20:27:22
【问题描述】:

我想将模型中文本字段的输入可能性限制为先前定义的数组。

如何使用像["foo","bar","foobar"] 这样的一维数组创建options_for_select

我试过了

form_for @mappings do |f|
  f.select(:mapping_type, options_for_select(["foo","bar","foobar"]), class: "..."

end

但是选择框出来的都是这样的:

<select name="section_mapping[mapping_type]" id="section_mapping_mapping_type">

与应有的相反:

<select name="mapping_type" >

编辑:

我将f.select 更改为select_tag,表单显示没有任何错误,但是当我提交它时,该字段为空

编辑 2:

f.collection_select(:mapping_type, options_for_select([...]), class: "..."

的工作原理是正确地提交带有值的表单,但不应用 HTML 类。这是为什么呢?

【问题讨论】:

    标签: ruby-on-rails forms drop-down-menu html-select


    【解决方案1】:

    基本上,您希望能够将您的集合选择绑定到对象的属性(在您的情况下,@mappings

    此外,从rails collection_select 上的文档中,它将采用以下选项:

    collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) public

    • 对象:在这种情况下,您将所选选项绑定到 (@mappings [f]) 的对象
    • 方法:对象的属性/属性(在本例中为mapping_type
    • collection: select 的集合 (["foo","bar","foobar"])
    • value_method:您要在提交时发回的值(注意这是method,这意味着您应该能够在对象上调用它。)稍后会详细介绍。
    • text_method:要在视图的选择选项上显示为文本的值(这也是上面的一种方法,稍后也会详细介绍)
    • 选项:您想要的任何其他选项,(例如:include_blank
    • html_options: 例如:idclass 等。

    关于value_methodtext_method,这些是应该在collection 上调用的方法,这意味着您的集合将是一个对象数组。

    为此,您可以有以下几点:

    class CollectionArr
      include ActiveModel::Model
    
      attr_accessor :name
      ARR = [
        {"name" => "foo"},
        {"name" => "bar"},
        {"name" => "foobar"}
      ]
    
      def self.get_collection
        ARR.collect do |hash|
          self.new(
            name: hash['name']
          )
        end
      end
    end
    

    从这里调用CollectionArr.get_collection 将返回一个对象数组,您可以在其中调用.name 以返回foobarfoobar。这使得使用collection_select 并从这里轻松交易:

    <%= f.collection_select : mapping_type, CollectionArr.get_collection, :name, :name, {:include_blank => "Select one"} %>
    

    一切都是绿色的......

    【讨论】:

    • 哇,非常感谢。这解决了我所拥有的问题,并且我学到了关于收藏的一件很酷的事情。您能否提供一个指向解释 self.get_collection 方法内容的文档的链接,特别是 self.new() 的作用。
    • 好吧,我写了那个方法......但这里的关键是 collect 循环给定的数组,以及 self.new 创建 CollectionArr 类的新实例.
    • 希望您的问题得到解答?
    猜你喜欢
    • 1970-01-01
    • 2010-12-07
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多