精華區beta Ruby 關於我們 聯絡資訊
原文在我的 Blog http://lightyror.blogspot.com/index.html 應該很多人有類似的想法吧? 今天兩個 tables ,他們的關聯不只一種 但是 Active Record 預設只有一種關聯性 舉個例子: User 這個 table 跟 Email 這個 table 是 1:m 的關係 email 這個欄位有 user_id -> 代表這個信的收信人是誰 還有 sender_user_id -> 代表這個信的寄件人是誰 今天如果使用 ActiveReocrd 的預設方式 class User < ActiveRecord::Base has_many :emails end class Email < ActiveRecord::Base belongs_to :user end 這樣只能使用 User.emails 代表這個人有多少信件要收 但是如果我們也想用 ActiveRecord 做到 User.send_emails 這樣 代表這個人有多少信件要寄呢? 我們可以使用 Virtual Model 來解決(我自己取的名字) class User < ActiveRecord::Base has_many :emails has_many :send_emails , :foreign_key => 'sender_user_id' end class Email < ActiveRecord::Base belongs_to :user end class SendEmail < Email belongs_to :user , :foreign_key => 'sender_user_id' end 如此就可以直接使用 User.messages還有User.send_messages 當然其實也可以用 Database 的 View Table 也是可以解決 -- lighty RoR 是一個介紹 lighttpd , SQLite , Ruby and Rails 的 Blog http://lightyror.blogspot.com/ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.230.114.97 ※ 編輯: giive 來自: 61.230.114.97 (09/05 13:33)