has_many和单表继承 [英] has_many and single table inheritance
问题描述
我在两个实体Feed和Post之间具有has_many关系.我也有特定类型的帖子,视频和照片.这是在数据库中使用单表继承结构化的.
I have a has_many relationship between two entities, Feeds and Posts. I also have specific types of posts, Videos and Photos. This is structured in the database using single table inheritance.
现在,我的Feed模型指定了Feed和Post(包括子类型)之间的has_many关系
Right now I have my Feed model specifying a has_many relationship between Feeds and Posts (including the subtypes)
class Feed < ActiveRecord::Base
has_many :posts
has_many :photos
has_many :videos
是否有更好,更常规的方式来指定?还是我所能得到的最简单?
Is there a better, more conventional way to specify this? Or is what I have as simple as it can get?
推荐答案
如果我对您的理解正确,那么您的帖子可以是视频或照片.正如Jaryl所说,您拥有的内容可能最容易理解/处理,但是,如果您想花哨的话,可以使用单表继承或多语言关联.
If i understand you correctly you have Posts and posts can be either video or photo. as Jaryl said what you have is probably the easiest to understand/handle however if you wanted to get fancy you could use single table inheritance or polymophic associations.
STI-示例(来自带有Rails 3rd Edition的敏捷Web开发)
STI - example (from 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)
然后您可以通过人找到它
you can then find it via person
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找到所有这些对象,但是您将获得照片和视频对象(如果发布的不是照片或视频,则返回对象)
and then you could find them all by Post.all but you would get back Photo and Video objects (and post objects if you have posts that are not photo or video)
不要忘记数据库表中的字符串:type
这篇关于has_many和单表继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!