ActiveRecord is not aware of timezones?

后端 未结 2 494
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 07:42

I have one question regarding to time zone

I have done the following yet, my activerecord is not still matching with my timezone when I do following query

         


        
2条回答
  •  醉梦人生
    2021-01-19 08:29

    create a migration with this content to remove the default value to created_at, so it's not filled by default on database level.

    change_column_default(:user_stocks, :created_at, nil)
    

    after that, when you create a new UserStock, you need to specify the created_at value, and there you can specify the created_at with the date of the user, taking care of the timezone.

    UserStock.create(created_at: Time.now.in_time_zone(user.time_zone).to_time...)
    

    or you can just maybe add it to a callback on the model so it's automatic everytime you create a UserStock, it change the value

    class UserStock < ActiveRecord::Base
      before_create :set_created_at
    
      private
        def set_created_at
          self.created_at = time.now.in_time_zone(self.user.time_zone).to_time
        end
    end
    

    so everytime you create one, the value is correct. with that it may work as expected.

    Another option if you don't need it just for that specific model and use them for all the user interaction, you can create a before filter on the application controller to set the time zone dinamically, something like

    class ApplicationController < ActionController::Base
      before_filter :set_time_zone
    
      def set_time_zone(&block)
        time_zone = current_user.try(:time_zone) || 'UTC'
        Time.use_zone(time_zone, &block)
      end
    end
    

提交回复
热议问题