我有两个实体之间的 has_many 关系,Feeds 和 Posts。我也有特定类型的帖子、视频和照片。这是使用单表继承在数据库中构建的。
现在我的 Feed 模型指定了 Feed 和帖子(包括子类型)之间的 has_many 关系
class Feed < ActiveRecord::Base
has_many :posts
has_many :photos
has_many :videos
有没有更好,更传统的方法来指定这一点?或者是我所拥有的尽可能简单?
最佳答案
如果我理解正确,您有帖子,帖子可以是视频或照片。正如 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)
然后你可以通过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 找到它们,但你会得到照片和视频对象(如果你有不是照片或视频的帖子,则发布对象)
不要忘记字符串 :type 在您的数据库表中
关于ruby-on-rails - has_many 和单表继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/889250/