如果我理解正确,您有帖子,帖子可以是视频或照片。正如 Jaryl 所说,你所拥有的可能是最容易理解/处理的,但是如果你想变得花哨,你可以使用单表继承或多态关联。
STI - 示例(来自 Agile Web Development with Rails 3rd Edition)
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 => 'john@doe.com', :balance => 78.29)
然后你可以通过人找到它
x = Person.find_by_name('John Doe')
x.class #=> Customer
x.email #=> john@doe.com
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 找到它们,但你会得到照片和视频对象(如果你有不是照片或视频的帖子,则发布对象)
不要忘记 db 表中的字符串 :type