use*_*579 0 ruby ruby-on-rails ruby-on-rails-3
我正在从DB中检索值并将其绑定在haml中.我试图在下拉选项中大写值.
models.rb
class EnumValue < ActiveRecord::Base
attr_accessible :enum_type, :name, :gdsn
scope :countries, EnumValue.where(enum_type: "country").order(:name)
end
Run Code Online (Sandbox Code Playgroud)
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')"}
Run Code Online (Sandbox Code Playgroud)
我试图EnumValue.countries.capitalize在haml中调用大写,我得到以下错误:undefined method capitalize for # ActiveRecord::Relation:0x123d0718>.
任何人都可以告诉我如何使用活动记录大写下拉值吗?
使用map于capitalize在阵列中的每个值:
EnumValue.countries.map(&:capitalize)
Run Code Online (Sandbox Code Playgroud)
顺便说一下你的用例titleize可能是更好的选择,因为它可以处理国家名称,包括多个单词:
"United States".capitalize
#=> "United states"
Run Code Online (Sandbox Code Playgroud)
鉴于:
"United States".titleize
#=> "United States"
Run Code Online (Sandbox Code Playgroud)
此外,您需要从返回的集合中获取国家/地区名称,因为您countries不返回国家/地区名称数组,但实例为EnumValue:
EnumValue.countries.map { |c| [c.name.titleize, c.id] }
Run Code Online (Sandbox Code Playgroud)