regmiprem
regmiprem

Reputation: 735

Nested attributes in mongodb confusion

I am using rails with database Mongodb. I am using devise . Devise has model name user.The id of the user is in

:id => current_user.id

I want to make a model such that when data is save from the form the id of the current user will also save in the collection. The model of my employee is

 class Employee
  include Mongoid::Document
  field :first_name, type: String
  field :middle_name, type: String
  field :last_name, type: String
  field :otherid, type: String
  field :licennum, type: String
  field :citizennum, type: String
  field :licenexp, type: String
  field :gender, type: String
   field :state, type: String
  field :marital_status, type: String
  field :country, type: String
  field :birthdate, type: String
  field :nickname, type: String
  field :description, type: String
  validates_presence_of :first_name

{ }

end

what should i put inside curly bracket so that when data is saved from that model it saves the current user id also inside it?

Upvotes: 0

Views: 265

Answers (1)

Marek Waligórski
Marek Waligórski

Reputation: 144

The code you show only contains personal information fields like birth date and such. I suppose the simplest solution would be to place them inside the User class, and change them using built-in devise actions such as devise/registrations#edit, which applies the changes to current_user as default.

Alternatively, if you want to keep Employee as a separate class, you could try embedding Employee in User class, like this:

class User 
  include Mongoid::Document

  embeds_one :employee
  (...)

class Employee
  include Mongoid::Document

  embedded_in :user

In this case, you would set up the relation at controller level, e.g.:

class EmployeesController < ApplicationController

  def create
    current_user.create_employee(params[:employee])
  end

After creation, you could access the user's ID from Employee class as user.id.

Upvotes: 1

Related Questions