Skip to content

Instantly share code, notes, and snippets.

@ise
Last active May 23, 2019 10:00
Show Gist options
  • Save ise/421b933e19e7da58e70cd380d8a184b9 to your computer and use it in GitHub Desktop.
Save ise/421b933e19e7da58e70cd380d8a184b9 to your computer and use it in GitHub Desktop.
mongoid has_and_belongs_to_many updated_at
class A
include Mongoid::Document
include Mongoid::Timestamps
field :hoge, type: String
has_and_belongs_to_many :bs
end
class B
include Mongoid::Document
include Mongoid::Timestamps
field :fuga, type: String
end
__END__
# Aのbsを更新してもAのupdated_atが更新されない件
# https://stackoverflow.com/questions/23661962/update-updated-at-on-related-has-and-belongs-to-many-models-in-mongoid/42364363
# https://jira.mongodb.org/browse/MONGOID-3252?jql=project%20%3D%20MONGOID%20AND%20status%20in%20(Open%2C%20%22In%20Progress%22%2C%20%22In%20Code%20Review%22%2C%20%22Needs%20Triage%22%2C%20%22Waiting%20(Blocked)%22%2C%20%22Waiting%20for%20Reporter%22%2C%20Investigating%2C%20Scheduled)%20AND%20text%20~%20%22Timestamps%20updated_at%22
> b1 = B.create
=> #<B _id: 5ce666e254ffa12711757d26, created_at: 2019-05-23 09:24:50 UTC, updated_at: 2019-05-23 09:24:50 UTC, fuga: nil>
> b2 = B.create
=> #<B _id: 5ce666e654ffa12711757d27, created_at: 2019-05-23 09:24:54 UTC, updated_at: 2019-05-23 09:24:54 UTC, fuga: nil>
> a = A.create(bs: [b1, b2])
=> #<A _id: 5ce666f154ffa12711757d28, created_at: 2019-05-23 09:25:05 UTC, updated_at: 2019-05-23 09:25:05 UTC, hoge: nil, b_ids: [BSON::ObjectId('5ce666e254ffa12711757d26'), BSON::ObjectId('5ce666e654ffa12711757d27')]>
> a.updated_at
=> Thu, 23 May 2019 09:25:05 UTC +00:00
> a.update_attributes(hoge: 'test')
=> true
> a.updated_at
=> Thu, 23 May 2019 09:25:19 UTC +00:00
# a.hogeの更新によりupdated_atも更新されている
> a.update_attributes(bs: [b2])
=> true
> a.updated_at
=> Thu, 23 May 2019 09:25:19 UTC +00:00
# a.bsの更新ではupdated_atは更新されていない
> a.bs
=> [#<B _id: 5ce666e654ffa12711757d27, created_at: 2019-05-23 09:24:54 UTC, updated_at: 2019-05-23 09:24:54 UTC, fuga: nil>]
# a.bs自体は更新されている
> a.update(bs: [b1, b2])
=> true
> a.updated_at
=> Thu, 23 May 2019 09:25:19 UTC +00:00
> a.bs = []
=> []
> a.save
=> true
> a.updated_at
=> Thu, 23 May 2019 09:25:19 UTC +00:00
# updateでもsaveでもダメ
> a.updated_at
=> Thu, 23 May 2019 09:25:19 UTC +00:00
> a.update_attributes(b_ids: [b1.id])
=> true
> a.updated_at
=> Thu, 23 May 2019 09:53:39 UTC +00:00
# こうすると更新される!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment