2016-03-07 18 views
1

降下來形式如何在鐵軌都被選擇時區從下拉

<%= time_zone_select :time_zone, ActiveSupport::TimeZone.all, nil, 
{:include_blank => false,:prompt=>"Select Time Zone"} %> 

時區選擇部分時區和提交表格後,當我做PARAMS [「的time_zone」]我得到

"#<ActiveSupport::TimeZone:0x00000001ff5450 @name=%22American Samoa%22, @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Pacific/Pago_Pago>, 
@current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: 439038000>,#<TZInfo::TimezoneOffset: -39600,0,SST>>,nil>>, 
#<ActiveSupport::TimeZone:0x00000002024bb0 @name=%22International Date Line West%22, @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: Pacific/Midway>,.............. 

我如何獲得選定的時區? 注:我保存時區中的字符串

回答

1

ActiveSupport::TimeZone對象上直接讓.name

irb(main):055:0> ActiveSupport::TimeZone.new("American Samoa").name 
=> "American Samoa" 

你可以可以用自定義的setter做到這一點。例如:

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 
+0

PLease ellaborate this.I無法理解此 –

+0

您可以通過'params [:time_zone] .name'獲取時區的名稱。通過在你的模型上創建一個自定義的setter,你可以直接將'params [:time_zone]'傳遞給你的模型,並將它轉換爲一個字符串進行存儲。 – max

0

它看起來像你的time_zone_select實際上是所謂time_zone而不是timezone所以嘗試做params['time_zone']

+0

這只是SO問題中的一個錯字。如果他使用錯誤的參數鍵,他會得到'nil'而不是'ActiveSupport :: TimeZone'。 – max