gpt4 book ai didi

ruby-on-rails - 在单个模型上设置 default_timezone

转载 作者:行者123 更新时间:2023-12-04 05:57:46 27 4
gpt4 key购买 nike

我从其他系统提供的数据库读取时遇到问题,因为我只能从中读取,并且日期时间存储在:本地时区。

与 Rails 3.2 应用程序一样,它“应该”存储在 :utc 中,就像我在这个应用程序中的所有其他表一样。

我只需要这个模型就可以在 :local 中。其余的必须在 :utc

我的本地时区是“UTC -04:00”

class ExternalTable < ActiveRecord::Base
establish_connection :otherdb
table_name :iseries_table <-- I have to live with it.
default_timezone = :local
puts "my default timezone is #{default_timezone}"

#lot's of defs
.....
end

运行“rails c”
> ExternalTable.inspect
«lot´s of attributes»
my default timezone is :utc <---utc!?. I have just set it to :local!?!?!?

> ExternalTable.default_timezone
:utc

> ExternalTable.default_timezone = :local
:local

> ExternalTable.default_timezone
:local <--- yeah, right. Setting it AFTER instantiated, works.

因此,Rails 似乎正在将所有 ActiveRecord.Base 时区设置回 :utc,在初始化之后,覆盖 ActiveRecord 的默认值,即 :local。

有很多方法可以解决这个问题,例如在每个 Controller 上设置一个 before_filter ,但它似乎不像 Rubyist。

最佳答案

不应该是:

self.default_timezone = :local

否则,您将创建一个名为“default_timezone”的局部变量。

如果您只想将它​​应用于一个类,您可以创建一个单例方法:
class ExternalTable < ActiveRecord::Base
def self.default_timezone
:local
end
end

有点hackish,但应该工作。

关于ruby-on-rails - 在单个模型上设置 default_timezone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9313900/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com