ActiveRecord is not aware of timezones?

↘锁芯ラ 提交于 2019-12-01 19:18:05

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!