6

我在两个实体 Feeds 和 Posts 之间有一个 has_many 关系。我也有特定类型的帖子、视频和照片。这是使用单表继承在数据库中构建的。

现在我的 Feed 模型指定了 Feed 和 Posts 之间的 has_many 关系(包括子类型)

class Feed < ActiveRecord::Base
  has_many :posts
  has_many :photos
  has_many :videos

有没有更好、更传统的方法来指定这个?还是我拥有的东西尽可能简单?

4

3 回答 3

5

如果我理解正确,您有帖子,帖子可以是视频或照片。正如 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)

然后你可以通过人找到它

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 找到它们,但你会得到照片和视频对象(如果你有不是照片或视频的帖子,则发布对象)

不要忘记 db 表中的字符串 :type

于 2009-06-02T14:03:20.227 回答
2

这几乎是你能做的最简单的事情。

好吧,如果照片可以被视为与视频相同,那么也许您可以取消 STI 并使用命名范围来为不同类型的内容提供访问器。

于 2009-05-21T19:19:24.667 回答
0

我同意问题中的示例非常简单。它已经在使用 STI 并明确说明了这些关联。

此外,您可以稍后删除 STI,并将 :photos 和 :videos 拆分为各自单独的表,而无需稍微更改 Feed 模型的代码。分数!

于 2009-07-08T04:46:59.060 回答