Association in rails using mongodb as database

大憨熊 提交于 2019-12-13 04:49:16

问题


I am using devise. It gives the current userid as

current_user.id

There are many users. There is a controller name as empsals_controller.rb

class EmpsalsController < ApplicationController

  def index
    @empsals = Empsal.all


  end

  def show
    @empsal = Empsal.find(params[:id])

  end

  def new
    @empsal = Empsal.new


  end


  def edit
    @empsal = Empsal.find(params[:id])
  end

  def create
    @empsal = Empsal.new(params[:empsal])

    respond_to do |format|
      if @empsal.save
        format.html { redirect_to @empsal, notice: 'Empsal was successfully created.' }
        format.json { render json: @empsal, status: :created, location: @empsal }
      else
        format.html { render action: "new" }
        format.json { render json: @empsal.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    @empsal = Empsal.find(params[:id])

    respond_to do |format|
      if @empsal.update_attributes(params[:empsal])
        format.html { redirect_to @empsal, notice: 'Empsal was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @empsal.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @empsal = Empsal.find(params[:id])
    @empsal.destroy

    respond_to do |format|
      format.html { redirect_to empsals_url }
      format.json { head :no_content }
    end
  end

The model of this controller is

class Empsal
  include Mongoid::Document
   belongs_to :paygrade
  field :salary_component, type: String
  field :pay_frequency, type: String
  field :currency, type: String
  field :amount, type: String
  field :comments, type: String
 validates_presence_of :pay_frequency

end

I want to make association with devise which have model user.rb such that related user can view their related data.

class User
  include Mongoid::Document
  include Mongoid::Timestamps
devise :database_authenticatable, :registerable, #:confirmable,
         :recoverable, :rememberable, :trackable, :validatable, :timeoutable, :timeout_in => 2.minutes
   field :role
end

回答1:


You have everything you need, except for setting the inverse association in the User model:

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :empsals # <<<<<<< added line

  devise :database_authenticatable, :registerable, #:confirmable,
         :recoverable, :rememberable, :trackable, :validatable, :timeoutable, :timeout_in => 2.minutes
   field :role
end

See the documentation at http://mongoid.org/en/mongoid/docs/relations.html#has_many

With this, you can do things like

@user.empsals # it will be a list of Empsal instances


来源:https://stackoverflow.com/questions/12706429/association-in-rails-using-mongodb-as-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!