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
实际上会更新用户对象以及DB记录的缓存关联,因为它是通过关联创建的。与使用Address.create
相反,在这种情况下,我希望需要重新加载用户对象。
答案 0 :(得分:0)
我认为,因为在大多数情况下它太昂贵且不必要。我通常把这些规格写成:
assert_equal Date.today, user.addresses.reload.first.created_at