2012-12-22 55 views
0

我發現了一些有關性病的好信息,但沒有看到我想要做的例子。這是我能想到的最好的例子。我希望能夠跟蹤兩個實體,但他們不需要自己的表。我只需要區分類型(STI可以這樣做),但我也需要知道一個實體是否以及如何與另一個實體相關。我將以書籍爲例。有些書只是書,但其他的實體書是多本書的集合。帶關係的單表繼承?

表:書

id | title | author_id | book_id 
1, 'Fellowship of the Ring, 34, (NULL)  # is a physical book 
2, 'The Two Towers', 34, (NULL)    # is a physical book 
3, 'American Gods', 1, (NULL)    # is a physical book 
4, 'Complete Lord Of the Rings', 34, (NULL) 
5, 'Fellowship of the Ring', 34, 4   # is collected within book id 4 
6, 'The Two Towers', 34, 4     # is also collected within book id 4 
etc. 

所以我希望能夠查詢書籍,所有書籍,瞭解它們是如何,如果通過「book_id」

的相互關係這是可能的Rails的?如果是這樣,它如何最好地實施?我可以在書籍模型中說'has_many:books'嗎?他們的陷阱或擔憂等等?

預先感謝您。

回答

4

像這樣的東西可能適合你的情況?

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?它將使查詢跨兩個較爲複雜,但可能使應用程序的其他部分更容易理解

UPDATE:對的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 

書數據庫表兩端添加belongs_to的到PhysicalBook,類名達看起來像

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 

ALSO:閱讀本 - http://rhnh.net/2010/07/02/3-reasons-why-you-should-not-use-single-table-inheritance

你可能不希望STI?數據模型將類似於以上但沒有STI,即系列/預訂

使用foreign_key中的has_many和belongs_to的可能會造成混淆:在這裏讀了 - http://guides.rubyonrails.org/association_basics.html

+0

我想這是不完全清楚我。我將如何查詢特定的集合以查看其中包含哪些書籍和書籍?我如何查看一本書並查看它是否在一個集合中,如果是,則與它關聯的特定集合的特定ID? – n8gard

+0

更新了更多細節 – house9

+0

非常有幫助。謝謝@ house9。 – n8gard