n8g*_*ard 1 ruby-on-rails ruby-on-rails-3 rails-activerecord
我已经找到了一些关于STI的好信息,但没有看到我想要做的例子.这是我能想到的最好的例子.我希望能够跟踪两个实体,但它们不需要自己的表.我只需要区分类型(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.
Run Code Online (Sandbox Code Playgroud)
因此,我希望能够查询所有书籍的书籍,并通过'book_id'了解它们是如何以及是否相互关联
这可能在Rails中吗?如果是这样,它如何最好地实施?我可以在书籍模型中说'has_many:books'吗?他们的陷阱或担忧等等?
先感谢您.
这样的事情可能适合你的情况?
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
Run Code Online (Sandbox Code Playgroud)
然后在查询时
# searches both Series and Physical
Book.where("title LIKE ?", "#{params[:title]}%")
# searches only Series
SeriesBook.where("title LIKE ?", "#{params[:title]}%")
Run Code Online (Sandbox Code Playgroud)
您可能会发现您真的希望您的模型与众不同吗?系列和书籍而不使用STI?它会使查询更复杂,但可能使应用程序的其余部分更容易理解
更新:将belongs_to添加到has_many关联上的PhysicalBook,类名
# 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
Run Code Online (Sandbox Code Playgroud)
书籍数据库表最终看起来像
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
Run Code Online (Sandbox Code Playgroud)
另外:阅读本文 - http://rhnh.net/2010/07/02/3-reasons-why-you-should-not-use-single-table-inheritance
你可能不想要STI?数据模型看起来与上面类似但没有STI,即系列/书
在has_many和belongs_to中使用foreign_key可能会令人困惑:请在此处阅读 - http://guides.rubyonrails.org/association_basics.html
| 归档时间: |
|
| 查看次数: |
1582 次 |
| 最近记录: |