Ruby on rails 如何从rails中的下拉列表中获取选定时区

Ruby on rails 如何从rails中的下拉列表中获取选定时区,ruby-on-rails,ruby,datetime,timezone,Ruby On Rails,Ruby,Datetime,Timezone,窗体中时区的下拉列表 <%= time_zone_select :time_zone, ActiveSupport::TimeZone.all, nil, {:include_blank => false,:prompt=>"Select Time Zone"} %> false,:prompt=>“选择时区”}%> 选择某个时区并提交表单后,当我执行params[“time_zone”]时,我会得到 “#, # 看起来您的时区选择实际上被称为时区而不是时区,因此请

窗体中时区的下拉列表

<%= time_zone_select :time_zone, ActiveSupport::TimeZone.all, nil,
 {:include_blank => false,:prompt=>"Select Time Zone"} %>
false,:prompt=>“选择时区”}%>
选择某个时区并提交表单后,当我执行params[“time_zone”]时,我会得到

“#,

# 看起来您的
时区选择
实际上被称为
时区
而不是
时区
,因此请尝试执行
参数['time\u zone']

只需在
活动支持::时区
对象上调用
.name

irb(main):055:0> ActiveSupport::TimeZone.new("American Samoa").name
=> "American Samoa"
您可以使用自定义设置器执行此操作。例如:

class City < ActiveRecord::Base
  # automatically convert ActiveSupport::TimeZone 
  # objects into a serializable string.
  def time_zone=(tz) 
    super(tz.try(:name) || tz)
  end
end

class CitiesController
  def create
    @city = City.create(city_params)
    respond_with(@city)
  end

  def city_params
    params.require(:city).permit(:time_zone)
  end
end
class City
请对此进行详细说明。我不明白您可以通过
params[:time\u zone]获取时区名称。name
。通过在您的模型上创建自定义setter,您可以传递
params[:time\u zone]
直接转到您的模型,它会将值转换为字符串存储。这只是SO问题中的一个输入错误。如果他使用了错误的参数键,他将得到
nil
,而不是
ActiveSupport::TimeZone
class City < ActiveRecord::Base
  # automatically convert ActiveSupport::TimeZone 
  # objects into a serializable string.
  def time_zone=(tz) 
    super(tz.try(:name) || tz)
  end
end

class CitiesController
  def create
    @city = City.create(city_params)
    respond_with(@city)
  end

  def city_params
    params.require(:city).permit(:time_zone)
  end
end