【问题标题】:Rails: updating an ActiveSupport::TimeWithZone field with Time by update_attributes failRails:使用 update_attributes 更新 ActiveSupport::TimeWithZone 字段失败
【发布时间】:2012-02-06 03:35:30
【问题描述】:

在带有 Postgresql 的 Rails 3.1.3 中,如果您将属性创建为 datetime,则其类使用 ActiveSupport::TimeWithZone。但是,任何可以解释这一点的人:

user=User.first
user.update_attributes(:last_signed_in_at => Time.now) #True, but record isn't updated
user.update_attribute(:last_signed_in_at, Time.now) #True, and record is updated
user.last_signed_in_at = Time.now
user.save #True, and the record is updated

update_attributes 与 update_attribute 不同,它检查验证。它失败的唯一原因可能是:

user.last_signed_in_at = ActiveSupport::TimeWithZone
Time.now.class = Time

有谁能解决吗?

【问题讨论】:

  • 你的用户模型中有attr_accessible吗?
  • 非常感谢,伙计。 attr_accessible:指定可以通过批量赋值设置的模型属性白名单,例如new(attributes)、update_attributes(attributes)或attributes=(attributes)
  • 这样就解决了你的问题:) ?
  • 是的,它与时间格式无关。赞赏!
  • 那我给它一个更清晰的答案,让后来者知道:)

标签: ruby-on-rails datetime activerecord update-attributes


【解决方案1】:

这是由于在 User 模型中设置了 attr_accessible

update_attribtue 所做的实际上与调用last_signed_in_at= 非常相似。在http://apidock.com/rails/ActiveRecord/Persistence/update_attribute中查看源代码

update_attributesupdate_attribute 之间的主要区别之一是 update_attributes 是进行质量分配,而 update_attribute 不是。

这就是为什么很明显是attr_accessible问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多