Rails Many-to-many relationships and polymorphism

Source: Internet
Author: User

1. Many-to-many relationships and the realization of multi-state students, courses, teachers

The relationship between the three is many-to-many, who shows the polymorphism of the class

Model Layer

Stu.rb

Has_many:summaries

Has_many:subjects,: Through =>:summaries,: Source =: Subject #实现多对多关系

Teacher.rb

Has_many:summaries,:as =:p eople,:d ependent =:d Estroy #实现多态

Has_many:subjects,: Through =>:summaries,: Source =: Subject #实现多对多关系

Subject.rb

Has_many:summaries

Has_many:teachers,: Through =>:summaries,: Source =:p Eople,: source_type = ' Teacher '

Has_many:stus,: through = Summaries,:source =:p eople,: source_type = ' Stu '

Summary.rb

Class Summary <activerecord::base

Belongs_to:p eople,:p olymorphic = True

Belongs_to:subject

End

Db/migrate Layer

Summary.rb

Create_table:summaries do |t|

t.integer:subject_id

T.string:p Eople_type

T.integer:p eople_id

End

Cases:

s = subject.new

t = teacher.new

S.teachers <<t

S.save

The data in the summary table is now updated

2, Name_scope (need to use the class name to call)

A) Named_scope:sub_stu,: conditions = "Shangke_type is null"

b) Named_scope:sub_stu,: conditions = "Shangke_type is null" do

def get_count

All.count:conditions = "id = 1"

End

End

This approach is equivalent to the way the DEF definition is performed on the contents of the conditions condition lookup. But in real execution, the DEF-defined method is converted into an SQL statement, executed with the condition statement.

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.