MongoMapper community has_many community

I have a problem with mongomapper associations. I have one user class name and another named Model. The user has many models, but ...

user = User.first
=> <User ...
user.models
=> []
Model.find_by_user_id(user.id.to_s)
=> <Model ...
Model.find_by_user_id(user.id.to_s).user == user
=> true

Class Code (Simplified):

class User
  include MongoMapper::Document

  # some keys definition

  many :models
end

class Model
  include MongoMapper::Document

  # some keys definitions

  belongs_to :user
end

What am I doing wrong?

+3
source share
3 answers

It looks like MM no longer uses the String format for the FK column, so

Model.find_by_user_id(user.id.to_s)

it should be

Model.find_by_user_id(user.id)

In addition, the data type in the Model.user_id column must be set to

key :user_id, Mongo::ObjectID

, , , , user_id String, "", , . , , .

+5

? , , .

0

ah, mm. :

class User
  include MongoMapper::Document

  # some keys definition

  many :models, :in => :model_ids
end

class Model
  include MongoMapper::Document

  # some keys definitions
  # no belongs_to necessary here
end

:

# use an existing object
u = User.create ...
m = Model.create ...

# and add the model to the user
u.models << m

# don't forget to save
u.save

# you can then check if it worked like so:
# u.model_ids  => [ BSON::ID 'your user id']

, .

0

Source: https://habr.com/ru/post/1727693/


All Articles