ActiveRecord is not aware of timezones?

后端 未结 2 498
伪装坚强ぢ
伪装坚强ぢ 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:12

    Did you try the query by specifying the range?

    Because you're trying to find the user_stocks that are created on some date. But notice that created_at is a datetime object and I guess your date variable might be just a date object.

    def stock_by_date(date)
      UserStock.where(created_at: date.midnight..date.end_of_day, user_id: current_user.id)
    end
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题