almost 4 years ago

有趣的關聯模式
在同一個model內就可以建立關聯
舉rails guide的例子
我們希望建立一個員工資料的model叫做Employee
但是employee之間應該會有上屬與下屬的關係,這代表什麼?
employee 1可能有很多下屬(employee2, employee3, employee4)
我希望可以在同一個model內就能找到employee 1的所有下屬
這時候就可以用self join
rails guide的範例就很清楚了,請看加上中文註解的版本:

In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:

class Employee < ActiveRecord::Base
  #一個employee有很多的下屬(subordinates),這些下屬是屬於Employee這個class的(也就是目前的class)

  #且這些下屬都歸一個manager管,這個manager可以從manager_id找到

  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"
  #員工都被manager管,而Manager本身也是Employee這個class的(也就是目前的class)

  belongs_to :manager, class_name: "Employee"
end

With this setup, you can retrieve @employee.subordinates and @employee.manager.

In your migrations/schema, you will add a references column to the model itself.

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.references :manager
      t.timestamps
    end
  end
end

參考資料
http://guides.rubyonrails.org/association_basics.html#self-joins

← 運用Rails Layout 與 Class繼承 實作Admin後台 Rails讓網址不再只顯示ID →
 
comments powered by Disqus