0

我正在使用设计。它将当前用户标识为

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
4

1 回答 1

1

除了在 User 模型中设置反向关联之外,您拥有所需的一切:

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
于 2012-10-03T13:20:42.750 回答