-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
I have two relations, has_many and has_and_belongs_to_many from User to Entry:
class Entry include Mongoid::Document field :content, type: String has_and_belongs_to_many :favorite_of, class_name: 'User', inverse_of: :favorites belongs_to :user, inverse_of: :entries, class_name: 'User' end class User include Mongoid::Document field :name, type: String has_and_belongs_to_many :favorites, class_name: 'Entry', inverse_of: :favorite_of has_many :entries, inverse_of: :user, class_name: 'Entry' end
Now when I add a favorite to a User, the favorite_ids array is saved properly, but when I read the user again, user.favorites is just []:
irb(main):001:0> u = User.create => #<User _id: 51223cd9e44f7b5ce2000001, name: nil, favorite_ids: nil> irb(main):002:0> e = Entry.create => #<Entry _id: 51223cdde44f7b5ce2000002, content: nil, favorite_of_ids: nil, user_id: nil> irb(main):003:0> u.favorites << e => [#<Entry _id: 51223cdde44f7b5ce2000002, content: nil, favorite_of_ids: ["51223cd9e44f7b5ce2000001"], user_id: nil>] irb(main):004:0> u.save => true irb(main):005:0> u.favorites => [#<Entry _id: 51223cdde44f7b5ce2000002, content: nil, favorite_of_ids: ["51223cd9e44f7b5ce2000001"], user_id: nil>] irb(main):006:0> exit $ rails c Loading development environment (Rails 3.2.12) irb(main):001:0> User.first.favorites => []
mongoid: 3.1.1
mongodb: 2.2.3
rails: 3.2.12
Although the setup is really simple, I put a test case online: https://github.com/pascalj/habtm-test