【问题标题】:Why doesn't Rails update its association cache when creating new records through the association?为什么 Rails 在通过关联创建新记录时不更新其关联缓存?
【发布时间】:2017-03-30 11:22:51
【问题描述】:
class User < ActiveRecord::Base
  has_many :addresses, -> { order("created_at DESC") }
end

class Address < ActiveRecord::Base
  belongs_to :user
end

class UserTest < ActiveSupport::TestCase
  test 'should return the last address the user created' do
    user = User.create!
    user.addresses.create!(created_at: Date.today - 1.day)
    user.addresses.create!(created_at: Date.today)
    assert_equal Date.today, user.addresses.first.created_at # note that .first here should actually return the last record created, when hitting the DB, due to the ordering specified in the association scope block
  end
end

这个断言会失败(user.addresses.first.created_at 返回Date.today-1.day),而如果我在断言之前执行user.reloaduser.addresses.reset,它将成功(user.addresses.first.created_at 然后返回Date.today)。

为什么 Rails 在通过关联创建新记录时不更新其关联缓存?

我原以为使用user.addresses.create 实际上会更新用户对象上的缓存关联以及数据库记录,因为它是通过关联创建的。与使用 Address.create 不同,在这种情况下,我预计需要重新加载用户对象。

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    我认为是因为在大多数情况下它太昂贵且没有必要。我通常把这些规格写成:

    assert_equal Date.today, user.addresses.reload.first.created_at
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      相关资源
      最近更新 更多