检查mongoid habtm关系是否改变了?

时间:2018-04-30 20:01:19

标签: ruby-on-rails mongodb ruby-on-rails-4 mongoid

如果在关系中添加了对象,我需要发送电子邮件

Account.rb型号

has_and_belongs_to_many :managers, class_name: 'User', inverse_of: :accounts

User.rb型号

has_and_belongs_to_many :accounts, inverse_of: :managers

在控制台中:

[15] pry(main)> a.reload
=> #<Account _id: 5ae71215a8abbc6378b4bee8, code: "ACC5", name: "Account5", manager_ids: []>
[16] pry(main)> u.reload
=> #<User _id: 5ae59b5da8abbc6f3d880a10, name: "Manager 1", account_ids: []>
[17] pry(main)> a.managers << u
=> [#<User _id: 5ae59b5da8abbc6f3d880a10, name: "Manager 1", account_ids: [BSON::ObjectId('5ae71215a8abbc6378b4bee8')]>]
[18] pry(main)> a.reload
=> #<Account _id: 5ae71215a8abbc6378b4bee8, code: "ACC5", name: "Account5", manager_ids: [BSON::ObjectId('5ae59b5da8abbc6f3d880a10')]>
[19] pry(main)> a.managers.select { |e| e.new_record? }.any?
=> false
[20] pry(main)> a.managers.any? {|a| a.changed?}
=> false

我已尝试使用a.managers.select { |e| e.new_record? }.any?a.managers.any? {|a| a.changed?},但我总是 false

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是通过可更改的mongoid模块Module: Mongoid::Changeable

解决的

https://www.rubydoc.info/github/mongoid/mongoid/Mongoid/Changeable

但是,你不应该这样建立关系:

a.managers << u

要检查a.manager_ids_changed?a.manager_ids_was等方法,您需要以这种方式创建关系:

a.manager_ids << u.id

谢谢!