我有两个实体,饲料和帖子has_many关系。我也有特定类型的帖子,视频和照片。这是使用单表继承在数据库中构建的。has_many和单表继承
现在我有我的饲料模型指定的饲料和职位之间的关系的has_many(包括亚型)
class Feed < ActiveRecord::Base
has_many :posts
has_many :photos
has_many :videos
有没有指定这个更好的,更传统的方式是什么?或者我所拥有的尽可能简单?
我有两个实体,饲料和帖子has_many关系。我也有特定类型的帖子,视频和照片。这是使用单表继承在数据库中构建的。has_many和单表继承
现在我有我的饲料模型指定的饲料和职位之间的关系的has_many(包括亚型)
class Feed < ActiveRecord::Base
has_many :posts
has_many :photos
has_many :videos
有没有指定这个更好的,更传统的方式是什么?或者我所拥有的尽可能简单?
如果我正确理解你,你有帖子和帖子可以是视频或照片。因为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找到他们所有,但(如果你有没有照片或视频的帖子,后对象)
不要忘了,你会回来的照片和视频对象字符串:在你的数据库表中输入
这几乎是最简单的你可以做的。
那么,如果照片可以视为与视频一样,那么也许您可以取消STI并使用命名范围为不同类型的内容提供访问者。
我同意问题中的例子非常简单。它已经在使用STI并明确说明了这些关联。此外,您可以稍后撷取STI,并将照片和:视频分割为各自的独立表格,而无需更改Feed模型的代码。得分了!
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