像这样的东西可能适合你的情况?
class Book < ActiveRecord::Base
# all attributes of a book
end
class SeriesBook < Book
has_many :books, :class_name => "PhysicalBook", :foreign_key => "parent_id"
end
class PhysicalBook < Book
belongs_to :series, :class_name => "SeriesBook", :foreign_key => "parent_id"
end
那么查询的时候
# searches both Series and Physical
Book.where("title LIKE ?", "#{params[:title]}%")
# searches only Series
SeriesBook.where("title LIKE ?", "#{params[:title]}%")
您可能会发现您真的希望您的模型与众不同?系列和书籍而不使用 STI?它会使两者的查询更加复杂,但可能会使应用程序的其余部分更容易理解
更新:将belongs_to 添加到PhysicalBook,has_many 关联上的类名
# How would I query a specific collection to see which and how many books it has within it?
series = SeriesBook.find(0000)
series.books.length # => how many
series.books.each do |book|
puts book.title
end
# How would I look at a book and see if it was in a collection and,
# if so, the specific ID of the specific collection to which it is associated
book = PhysicalBook.find(0000)
puts book.series.title
puts book.series.id
图书数据库表最终看起来像
id # primary key
title
# other book columns ....
type # STI
parent_id # nullable, used by physical book when part of a series, points to books.id on the series book
另外:阅读此内容-http: //rhnh.net/2010/07/02/3-reasons-why-you-should-not-use-single-table-inheritance
你可能不想要性病?数据模型看起来与上面类似,但没有 STI,即系列/书籍
在 has_many 和 belongs_to 中使用 foreign_key 可能会令人困惑:在此处阅读 - http://guides.rubyonrails.org/association_basics.html