vri*_*h88 6 ruby-on-rails has-many single-table-inheritance
我在两个实体,Feeds和Posts之间有一个很好的关系.我还有特定类型的帖子,视频和照片.这是使用单表继承在数据库中构建的.
现在我的Feed模型指定了Feeds和Posts之间的has_many关系(包括子类型)
class Feed < ActiveRecord::Base
has_many :posts
has_many :photos
has_many :videos
Run Code Online (Sandbox Code Playgroud)
是否有更好,更传统的方式来指定它?或者是我能拥有的那么简单?
如果我理解你,你有帖子和帖子可以是视频或照片.正如Jaryl所说,你所拥有的东西可能是最容易理解/处理的,但如果你想得到想象,你可以使用单表继承或多态关联.
STI - 示例(来自使用Rails第3版的Agile Web开发)
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
Run Code Online (Sandbox Code Playgroud)
所以如果你创建了一个客户
Customer.create(:name => 'John Doe', :email => 'john@doe.com', :balance => 78.29)
Run Code Online (Sandbox Code Playgroud)
然后你可以通过人找到它
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
Run Code Online (Sandbox Code Playgroud)
所以你可以拥有
class Post < ActiveRecord::Base
end
class Photo < Post
end
class Video < Post
end
Run Code Online (Sandbox Code Playgroud)
然后你可以通过Post.all找到所有这些,但你会得到照片和视频对象(如果你的帖子不是照片或视频,也可以发帖子)
不要忘记字符串:在db表中输入
| 归档时间: |
|
| 查看次数: |
7559 次 |
| 最近记录: |