zoukankan      html  css  js  c++  java
  • Ruby on rails开发从头来(五十八) ActiveRecord基础(自关联)

      或许存在这样的情况,在一个表中,一条记录关联到表中的另一条记录,例如,公司中的每个雇员都有上级和下级,而他们同时又是雇员,在Rails中你可以这样使用Employee类:

     

    class Employee < ActiveRecord::Base

    belongs_to :manager,

    :class_name => "Employee",

    :foreign_key => "manager_id"

    belongs_to :mentor,

    :class_name => "Employee",

    :foreign_key => "mentor_id"

    has_many :mentored_employees,

    :class_name => "Employee",

    :foreign_key => "mentor_id"

    has_many :managed_employees,

    :class_name => "Employee",

    :foreign_key => "manager_id"

    end

    让我们使用一些数据,这里雇员ClemDawn都有上级和下级:

    Employee.delete_all

    adam = Employee.create(:id => 1, :name => "Adam")

    beth = Employee.create(:id => 2, :name => "Beth")

    clem = Employee.new(:name => "Clem")

    clem.manager = adam

    clem.mentor = beth

    clem.save!

    dawn = Employee.new(:name => "Dawn")

    dawn.manager = adam

    dawn.mentor = clem

    dawn.save!

    现在我们可以通过关联,来回答“X的下属是谁?”,“Y的上级是谁?”。

    p adam.managed_employees.map {|e| e.name} # => [ "Clem", "Dawn" ]

    p adam.mentored_employees # => []

    p dawn.mentor.name # => "Clem"

  • 相关阅读:
    java面试常见的类
    Day6
    DAY5
    Day4
    Day3
    Day2
    Day1
    echarts3关系图:力引导布局, 固定某些节点
    Hbuilder中配置cmd
    webpack 学习
  • 原文地址:https://www.cnblogs.com/dahuzizyd/p/ruby_rails_study_58.html
Copyright © 2011-2022 走看看