国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Ruby > 正文

詳解ruby on rails中Model的關聯

2020-02-24 15:36:14
字體:
來源:轉載
供稿:網友

大多數網站在建站的時候都會考慮自己的安全性,而驗證碼檢測已成為一個必不可少的過程,Ruby的驗證代碼實現起來更簡單、更方便,本文是武林技術頻道小編為大家帶來的詳解ruby on rails中Model的關聯,一起來學習吧!

一:一對多

例如:
王媽媽有兩個孩子,小明和小亮。可以說,王媽媽,有多個孩子。也可以說:小明,有一個媽媽;小王,有一個媽媽。我們一般在設計表的時候,是這樣設計的:
mothers表中id和name
sons表中有id和name
為了增加邏輯關系,主外鍵關系,會在多的一方,增加一列,所以sons表中有三列,id和name和mother_id(對應了mothers表的id)
普通SQL:

select test_associate.mothers.name from test_associate.mothers inner join test_associate.sons on sons.mother_id = mothers.id where sons.name = '小李'

ruby代碼:

class Mother  has_many :sons end class Son  belongs_to :mother end

解釋:一個媽媽又多個孩子,一個兒子屬于一個媽媽。
我們在rails console可以測試下:
xiao_wang = Son.first?
mom = xiaowang.mother

這個 .mother 方法就是由 class Son的belongs_to :mother這句話生成的。
也就是相當于轉換成了一下的sql語句:

select * from mothers   join sons   on sons.mother_id = mothers.id   where sons.id = 1

詳細解釋:

A:belongs_to :mother
B:belongs_to :mother, :class => 'Mother', :foreign_key => 'mother_id'
A=B

這個就是Rails最典型的根據慣例來編程,聲明哪個表對應的是哪個class,再在class之間聲明好關聯關系。
1.belongs_to :mother, rails就能判斷出: mothers 表,是一的那一端。 而當前class 是: "class Son", 那么rails 就知道了 兩個表的對應關系。
2.:class => 'Mother', 表示, 一的那一端, 對應的model class是Mother. 根據rails的慣例, Mother model對應的是 數據庫中的 mothers 表。
3.:foreign_key => 'mother_id', rails就知道了, 外鍵是 'mother_id'. 而一對多關系中, 外鍵是保存在 多的那一端(也就是 sons, 所以說,在 sons表中, 必須有一個列, 叫做: mother_id )
所以, 這個復雜的SQL 條件就齊備了, 可以生成了。
上面的ruby代碼,配置好之后, 就可以這樣調用:

son = Son.firstson.mother # .mother方法, 是由 class Son 中的 belongs_to 產生的。mother = Mother.firstmother.sons  # .sons 方法, 是由 class Mother 中的 hash_many 產生的。

二:一對一,比較簡單,也不常用,這里不介紹。(老公和老婆)

三:多對多

例如:
一個學生,有多個老師,(學習了多門課程)
一個老師,可以教多個孩子(教一門課程,但是有好多學生來聽這個課程)
我們往往會這樣做:
students有id和name兩個字段
teachers有id和name兩個字段
放在任何一個表中都不合適,這是我們需要一張中間表,也就是橋梁表。
lessons有id和name和student_id和teacher_id
原始SQL:

select teachers.*, students.*, lessons.*   from lessons from teachers ,   join teachers   on lessons.teacher_id = teachers.id   join students   on lessons.student_id = students.id    where students.name = '小王'

Ruby代碼:

class Student  has_many :lessons  has_many :teachers, :through => :lessons end

提示:has_many :teachers, :through => :lessons 相當于
has_many :teachers, :class => 'Teacher', :foreign_key => 'teacher_id', :throught => :lessons
class Teachers?
? has_many :lessons?
? has_many :students, :through => :lessons?
end

查看小王的老師有哪些,同上面的原始SQL語句。

Student.find_by_name('小王').teachers

以上就是詳解ruby on rails中Model的關聯,建議大家收藏該文章,相信這里的內容是對你有幫助的,也建議你經常來武林技術頻道逛一逛,相信有用的信息就在這里。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 尼木县| 邹城市| 鲁甸县| 灵石县| 正宁县| 准格尔旗| 石景山区| 吉安县| 民和| 仁布县| 昌乐县| 庄浪县| 河东区| 澄迈县| 旅游| 怀宁县| 锡林浩特市| 同江市| 太仆寺旗| 施秉县| 盐津县| 永宁县| 旌德县| 烟台市| 肃北| 铁岭县| 惠水县| 镇雄县| 天门市| 大丰市| 高州市| 邯郸县| 长泰县| 建平县| 育儿| 辽中县| 石楼县| 庆元县| 安多县| 遂川县| 普宁市|