0

私はデバイスを使用しています。現在のユーザーIDを次のように指定します

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

ユーザーモデルで逆アソシエーションを設定することを除いて、必要なものはすべて揃っています。

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 に答える