【发布时间】: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.reload 或user.addresses.reset,它将成功(user.addresses.first.created_at 然后返回Date.today)。
为什么 Rails 在通过关联创建新记录时不更新其关联缓存?
我原以为使用user.addresses.create 实际上会更新用户对象上的缓存关联以及数据库记录,因为它是通过关联创建的。与使用 Address.create 不同,在这种情况下,我预计需要重新加载用户对象。
【问题讨论】:
标签: ruby-on-rails activerecord associations