has_many and single table inheritance

心已入冬 提交于 2019-12-09 12:35:48

问题


I have a has_many relationship between two entities, Feeds and Posts. I also have specific types of posts, Videos and Photos. This is structured in the database using single table inheritance.

Right now I have my Feed model specifying a has_many relationship between Feeds and Posts (including the subtypes)

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

Is there a better, more conventional way to specify this? Or is what I have as simple as it can get?


回答1:


If i understand you correctly you have Posts and posts can be either video or photo. as Jaryl said what you have is probably the easiest to understand/handle however if you wanted to get fancy you could use single table inheritance or polymophic associations.

STI - example (from 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

So if you create a customer

Customer.create(:name => 'John Doe', :email => 'john@doe.com', :balance => 78.29)

you can then find it via 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

So you could have

class Post < ActiveRecord::Base
end
class Photo < Post
end
class Video < Post
end

and then you could find them all by Post.all but you would get back Photo and Video objects (and post objects if you have posts that are not photo or video)

don't forget the string :type in your db table




回答2:


This is pretty much the simplest you can do.

Well, if photos could be treated the same as videos, then perhaps you could do away with STI and use named scopes to provide accessors to different types of content.




回答3:


I agree that the example in the question is as simple as it gets. It is already using STI and clearly states the associations.

Also, you could rip out the STI later, and split :photos and :videos into their own separate tables without changing the Feed model's code one bit. Score!



来源:https://stackoverflow.com/questions/889250/has-many-and-single-table-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!