大写下拉(选项)值
Capitalize the drop down (option) values
我正在从数据库中检索值并将其绑定到 haml 中。我正在尝试将下拉选项中的值大写。
models.rb
class EnumValue < ActiveRecord::Base
attr_accessible :enum_type, :name, :gdsn
scope :countries, EnumValue.where(enum_type: "country").order(:name)
end
form.html.haml
.offset1.span2
= f.association :country, :collection => EnumValue.countries,:include_blank => "Select Country",:label => "Country of Origin",:selected =>@records.country_id ? @records.country_id, :input_html => {:onchange =>"setGdsnName(this.value,'country')"}
我试图在 haml 中调用 capitalize on EnumValue.countries.capitalize
,但出现以下错误:undefined method capitalize for # ActiveRecord::Relation:0x123d0718>
.
谁能告诉我如何使用活动记录将下拉列表中的值大写?
使用 map
到 capitalize
数组中的每个值:
EnumValue.countries.map(&:capitalize)
顺便说一句,对于您的用例 titleize
可能是更好的选择,因为它可以处理包含多个单词的国家/地区名称:
"United States".capitalize
#=> "United states"
鉴于:
"United States".titleize
#=> "United States"
此外,您需要从 returned 集合中获取国家名称,因为您的 countries
不是 return 国家名称数组,而是 EnumValue
的实例:
EnumValue.countries.map { |c| [c.name.titleize, c.id] }
如果你在EnumValue
中定义了一个titleized_contries
方法:
def titleized_contries
countries.map(&:titleize)
end
你可以优雅地使用collection_select
f.collection_select(:country, EnumValue.countries, :id, titleized_contries, include_blank: "Select Country", label: "Country of Origin")
我正在从数据库中检索值并将其绑定到 haml 中。我正在尝试将下拉选项中的值大写。
models.rb
class EnumValue < ActiveRecord::Base
attr_accessible :enum_type, :name, :gdsn
scope :countries, EnumValue.where(enum_type: "country").order(:name)
end
form.html.haml
.offset1.span2
= f.association :country, :collection => EnumValue.countries,:include_blank => "Select Country",:label => "Country of Origin",:selected =>@records.country_id ? @records.country_id, :input_html => {:onchange =>"setGdsnName(this.value,'country')"}
我试图在 haml 中调用 capitalize on EnumValue.countries.capitalize
,但出现以下错误:undefined method capitalize for # ActiveRecord::Relation:0x123d0718>
.
谁能告诉我如何使用活动记录将下拉列表中的值大写?
使用 map
到 capitalize
数组中的每个值:
EnumValue.countries.map(&:capitalize)
顺便说一句,对于您的用例 titleize
可能是更好的选择,因为它可以处理包含多个单词的国家/地区名称:
"United States".capitalize
#=> "United states"
鉴于:
"United States".titleize
#=> "United States"
此外,您需要从 returned 集合中获取国家名称,因为您的 countries
不是 return 国家名称数组,而是 EnumValue
的实例:
EnumValue.countries.map { |c| [c.name.titleize, c.id] }
如果你在EnumValue
中定义了一个titleized_contries
方法:
def titleized_contries
countries.map(&:titleize)
end
你可以优雅地使用collection_select
f.collection_select(:country, EnumValue.countries, :id, titleized_contries, include_blank: "Select Country", label: "Country of Origin")