ruby-on-rails - has_many 和单表继承

标签 ruby-on-rails has-many single-table-inheritance

我有两个实体之间的 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/

相关文章:

html - 如何对 Rails 上的图像进行 SCSS 更改

yii2 - 如何在Yii2的ON条件下使用常数hasMany关系

ruby-on-rails - 仅删除具有多个关系

ruby-on-rails - 使用 STI 时如何将 ActiveRecord 对象转换为另一个类?

mysql - hibernate中使用单表策略时将父类(super class)的实例更新为子类的实例

ruby-on-rails - 添加 devise gem 后登录页面出错

ruby-on-rails - 如何将 action 'current_user' 添加到 restful 'user'?

ruby-on-rails - 使用 ActiveMerchant 和 PayPal 在实时网站上接受虚拟信用卡

ruby-on-rails - ActiveRecord has_many 其中表 A 中的两列是表 B 中的主键

ruby - 迁移到单表继承时的 Rails 4 更新类型