在单个模型上设置default_timezone
我在从其他系统提供的数据库读取数据时遇到问题,因为我只能从中读取数据,并且日期时间存储在:本地时区中。
与 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。
有很多方法可以解决这个问题,例如在每个控制器上设置 before_filter ,但它看起来不像 Rubyist 那样。
I've got an issue reading from a database that's fed from other system, as in I just can read from it, and has datetime stored in :local timezone.
As with Rails 3.2 apps, it "should" be stored in :utc as all my other tables in this app.
I need just this model to be in :local. The rest have to be in :utc
My local timezone is '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
Running "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.
So, it seems Rails is setting all ActiveRecord.Base timezone back to :utc, after it is initialized, overriding ActiveRecord's default, that is :local.
There are a lot's of ways to go arround this, such as setting a before_filter on every controller , but it just doesn't seem Rubyist like.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不应该是这样:
否则您将创建一个名为“default_timezone”的局部变量。
如果您只想将其应用于一个类,您可以创建一个单例方法:
有点hackish,但应该可以工作。
Shouldn't it be:
Otherwise you are creating a local variable called "default_timezone".
If you just want it to apply to one class you could create a singleton method:
A little hackish but should work.
在 Rails 6 中,您已经可以编写您的问题,它将设置从 BiLocalTimeRecord 继承的每个类,日期时间为本地时间:
In Rails 6, you can already write as your question, which will set every class inherited from BiLocalTimeRecord, datetime as local time: