协会使用的MongoDB数据库轨(Association in rails using mongod

2019-11-01 02:48发布

我使用的色器件。 它给当前的userid

current_user.id

有很多用户。 有一个控制器名称为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

该控制器的模型

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

我想和具有模型user.rb使得相关用户可以查看他们的相关数据色器件关联。

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

Answer 1:

你有你需要的,除了设置在用户模型中的负相关的一切:

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

请阅读文档http://mongoid.org/en/mongoid/docs/relations.html#has_many

有了这个,你可以做这样的事情

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


文章来源: Association in rails using mongodb as database