Ruby on Rails development from scratch (58)-ActiveRecord Foundation (Self-Association)

Source: Internet
Author: User
Tags ruby on rails

Perhaps there is a situation where a record is associated with another record in a table, for example, every employee in the company has superiors and subordinates, and they are employees, and you can use the employee class in rails:

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

Let's use some data, where employees Clem and Dawn both have superiors and subordinates:

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
C lem.save!
Dawn = employee.new (: Name => "Dawn")
Dawn.manager = Adam
dawn.mentor = Clem
dawn.save!

Now we can answer by association, "who is X's subordinate?" "," Who is the superior of Y? ”。

P Adam.managed_employees.map {|e| e.name} # => ["Clem", "Dawn"]
P adam.mentored_employees # => []
p DAWN.M Entor.name # => "Clem"
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.