rails 多對多關係及多型

2021-07-02 04:05:47 字數 1313 閱讀 2439

1、多對多關係並實現多型  學生、課程、老師

三者之間彼此為多對多的關係,誰上課體現了多型的性

model層

stu.rb

has_many :summaries

has_many :subjects, :through =>:summaries, :source => :subject    #實現多對多關係   

teacher.rb

has_many :summaries,:as => :people,:dependent => :destroy     #實現多型

has_many :subjects, :through =>:summaries, :source => :subject    #實現多對多關係

subject.rb

has_many :summaries

has_many :teachers, :through =>:summaries, :source => :people, :source_type => 'teacher'

has_many :stus, :through => :summaries,:source => :people, :source_type => 'stu'

summary.rb

class summary belongs_to :people, :polymorphic => true

belongs_to :subject

enddb/migrate層

summary.rb

create_table :summaries do |t|

t.integer :subject_id

t.string  :people_type

t.integer :people_id

end例:

s = subject.new

t = teacher.new

s.teachers 此時summary表中的資料會被更新

2、name_scope(需要用類名來呼叫)

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"

endend

此種方式相當於對conditions的條件查詢出的內容執行def定義的方法。但是在真正執行的時候,def定義的方法會被轉化為sql語句,和condition的語句一起執行。

多對多關係

實體模型中相關的模型之間為了方便查詢需要做到你中有我 我中有你 一對多表設計上是在多方應用少方的主鍵作為外來鍵約束 模型上需要在多方加入乙個少方模型物件的屬性,在少方加入乙個多方物件的列表 語法 少方物件 db.relationship 少方模型名 backref db.backref xxlist...

Flask sqlalchemy多對多關係

from flask import flask from flask sqlalchemy import sqlalchemy article tag db.table article tag db.column article id db.integer,db.foreignkey article...

多對多關係對映

需要用到 manytomany註解,然後在需要維護關係的一方,加上 jointable註解。必須指定乙個維護關係,否則會導致關係表id重複出現錯誤。jointable 有以下屬性,joincolumns 設定該實體類對映在關係表中的外來鍵列名和參照列,inversecolumns 設定和該實體類關聯...