2009-05-20 68 views
6

我有兩個實體,飼料和帖子has_many關係。我也有特定類型的帖子,視頻和照片。這是使用單表繼承在數據庫中構建的。has_many和單表繼承

現在我有我的飼料模型指定的飼料和職位之間的關係的has_many(包括亞型)

class Feed < ActiveRecord::Base 
    has_many :posts 
    has_many :photos 
    has_many :videos 

有沒有指定這個更好的,更傳統的方式是什麼?或者我所擁有的儘可能簡單?

回答

4

如果我正確理解你,你有帖子和帖子可以是視頻或照片。因爲Jaryl表示你所擁有的可能是最容易理解/處理的,但是如果你想要使用單表繼承或多態關聯,

STI - 例如(來自敏捷Web開發使用Rails第3版)

create_table :people, :force => true do |t| 
    t.string :type 

    #common attributes 
    t.string :name 
    t.string :email 

    #attributes for type=Customer 
    t.decimal :balance, :precision => 10, :scale => 2 

    #attributes for type=Employee 
    t.integer :reports_to 
    t.integer :dept 

    #attributes for type=Manager 
    #none 
end 

class Person < ActiveRecord::Base 
end 

class Customer < Person 
end 

class Employee < Person 
    belongs_to :boss, :class_name => "Manager", :foreign_key => :reports_to 
end 

class Manager < Person 
end 

因此,如果你創建一個客戶

Customer.create(:name => 'John Doe', :email => '[email protected]', :balance => 78.29) 

然後你可以通過人找到它

x = Person.find_by_name('John Doe') 
x.class #=> Customer 
x.email #=> [email protected] 
x.balance #=> 78.29 
x.some_customer_class_method # will work because the Person.find method returned a Customer object 

所以你可以有

class Post < ActiveRecord::Base 
end 
class Photo < Post 
end 
class Video < Post 
end 

,然後你可以通過Post.all找到他們所有,但(如果你有沒有照片或視頻的帖子,後對象)

不要忘了,你會回來的照片和視頻對象字符串:在你的數據庫表中輸入

+1

http://stackoverflow.com/questions/3231889/rails-sti-with-inheriting-children我想弄清楚如何讓STI成爲一個子對象,所以在給定的例子中,我將如何編寫「 Person belongs_to:company「和」Company has_many:persons「? – Rabbott 2010-07-27 04:10:02

1

這幾乎是最簡單的你可以做的。

那麼,如果照片可以視爲與視頻一樣,那麼也許您可以取消STI並使用命名範圍爲不同類型的內容提供訪問者。

0

我同意問題中的例子非常簡單。它已經在使用STI並明確說明了這些關聯。此外,您可以稍後擷取STI,並將照片和:視頻分割爲各自的獨立表格,而無需更改Feed模型的代碼。得分了!