9
我在閱讀關於自引用has_many:今天通過數據情況,因爲我試圖構建一個使用它們的Rails應用程序。我在互聯網上找到這個example situation,我對此有疑問。讓我從這個傢伙的博客張貼此示例代碼:自引用has_many問題:通過Rails中的關聯
create_table :animals do |t|
t.string :species
end
create_table :hunts do |t|
t.integer :predator_id
t.integer :prey_id
t.integer :capture_percent
end
class Animal < ActiveRecord::Base
has_many :pursuits, :foreign_key => 'predator_id',
:class_name => 'Hunt',
:dependent => :destroy
has_many :preys, :through => :pursuits
has_many :escapes, :foreign_key => 'prey_id',
:class_name => 'Hunt',
:dependent => :destroy
has_many :predators, :through => :escapes
end
class Hunt < ActiveRecord::Base
belongs_to :predator, :class_name => "Animal"
belongs_to :prey, :class_name => "Animal"
end
比方說,我建立了一個網頁,列出在其數據庫中的第一個動物。這個標題下是一個百分比列表(capture_percent)。每個百分比指的是本頁面動物追捕的動物,但它不會告訴你動物的名字,只是百分比。點擊任何給定的百分比然後將帶您到相應的動物頁面。
這是一個很難回答的問題,我知道,但我試圖弄清楚。我需要爲CapturePercent創建一個單獨的表嗎?