Reputation: 133
I'm new with Mongoid/MongoDB with Rails. I want to create has_and_belongs_to_many asscoiation between User and Project.
class Project
include Mongoid::Document
field :title, type: String
field :description, type: String
validates_presence_of :title, :description
has_and_belongs_to_many :users
end
class User
include Mongoid::Document
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
## Database authenticatable
field :email, type: String, default: ""
field :encrypted_password, type: String, default: ""
## Recoverable
field :reset_password_token, type: String
field :reset_password_sent_at, type: Time
## Rememberable
field :remember_created_at, type: Time
## Trackable
field :sign_in_count, type: Integer, default: 0
field :current_sign_in_at, type: Time
field :last_sign_in_at, type: Time
field :current_sign_in_ip, type: String
field :last_sign_in_ip, type: String
## Confirmable
# field :confirmation_token, type: String
# field :confirmed_at, type: Time
# field :confirmation_sent_at, type: Time
# field :unconfirmed_email, type: String # Only if using reconfirmable
## Lockable
# field :failed_attempts, type: Integer, default: 0 # Only if lock strategy is :failed_attempts
# field :unlock_token, type: String # Only if unlock strategy is :email or :both
# field :locked_at, type: Time
has_and_belongs_to_many :projects
end
But when I go to the console, it looks like they are not connected.
{ "_id" : ObjectId("564ddf63c705146553000001"), "title" : "Project 1 ", "description" : "....." }
{ "_id" : ObjectId("564dddc6c70514618c00000b"), "email" : "[email protected]", "encrypted_password" : "$2a$10$xUAdz9V64IEH9oufE3kYauzZ/.xa5GBr/0lapZDnSkwca40jH8/i6", "sign_in_count" : 1, "reset_password_token" : null, "reset_password_sent_at" : null, "last_sign_in_at" : ISODate("2015-11-19T14:33:43.293Z"), "current_sign_in_at" : ISODate("2015-11-19T14:33:43.293Z"), "last_sign_in_ip" : "::1", "current_sign_in_ip" : "::1" }
I expected to have project_ids for User and user_ids for Project. What am I doing wrong?
Upvotes: 1
Views: 430
Reputation: 133
I got it! I simply should have watched in rails console, not a mongodb console. I still don't understand, why these consoles show different results. But in rails console there were my project_ids for User and user_ids for Project. So HABTM works!
Upvotes: 0