rubymongodbmongomapperdatabase

User relation to group and company MongoMapper


I have need to create a system where a user can login with a user account where a user is a member of a group like admin or editor. Also a user is a member of a company. in both cases of groups and company's they can have multiple users but user can be only a member of one company and multiple groups.

The relations that i can get out of this is that a group has many users, company has many users, user has one company, user has many groups.

but my problem then how do i create this with ruby and mongoMapper? i have look at the documentation and other sources but did not find a good solution or explanation on how to use or set this up.

If anyone have a better way of doing it also welcome.

these are the current classes i have written.

class User
  include MongoMapper::Document

  key :username, String
  key :password, String
  key :name, String

  belongs_to :group
  belongs_to :company
end


class Group
  include MongoMapper::Document

  key :group_id, Integer
  key :name, String
  key :accesLevel, Integer

  many :user
end


class Company 
  include MongoMapper::Document

  key :name, String

  many :user
end

Solution

  • After some more google searching i have found a solution.

    first i made the user class look like this:

    class User
      include MongoMapper::Document
    
      key :username, String
      key :password, String
      key :name, String
      key :companyID
      key :groupID
      timestamps!
    
    end
    

    then the group and company class like this:

    class Company 
      include MongoMapper::Document
    
      key :name, String
      timestamps!
    
    end
    
    
    
     class Group
      include MongoMapper::Document
    
      key :name, String
      key :accesLevel, Integer
      timestamps!
    
    end
    

    With these classes in place i changed my controller to first create a company and then a group these could also be loaded but for the ease of testing it was not necessary to do this so that i didn't need to write the code for this.

    company = Company.new
    company.name = "comp"
    
    group = Group.new
    group.name = "admin"
    
    user = User.new
    user.name = "user1"
    user.username = "user1"
    user.password = "passuser1"
    
    user.groupID = group.id
    user.companyID = company.id
    
    db_config = YAML::load(File.open('./dbconfig.yml'))
    
    MongoMapper.connection = Mongo::Connection.new(db_config['hostname'])
    MongoMapper.database = db_config['name']
    
    company.save
    group.save
    user.save