假设我有一个包含2个模型的简单场景,Book
和Category
s,其中每本书都属于许多类别。
我想根据here和here将Category
数据移出数据库。
我的类别类看起来像这样:
class Category
FICTION = Category.new(1, 'Fiction')
NON_FICTION = Category.new(2, 'Non Fiction')
CONTUTERS = Category.new(3, 'Contuters')
def initialize(id, name)
@id = id
@name = name
end
end
我有一个books_categories
表,如下所示:
| book_id | category_id |
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
...
我应该如何在我的书类和数据库中对此进行建模?
理想情况下,我希望它看起来像这样:
class Book < ActiveRecord::Base
has_many :categories
end
但是可以在类别中添加或删除本书。
一种方法是使用embedded associations。我不喜欢的是它使得数据库难以检查。
是否有其他方法,可能维护现有的books_categories
表?
答案 0 :(得分:1)
我查看了https://github.com/pboling/flag_shih_tzu,但最后,我使用简单的has_many
联接模型实现了这一点。我在id
表中添加了books_categories
列,重命名为book_categories
并在Book
上实施了自定义getter / setter:
class Category
ALL = [
FICTION = Category.new(1, 'Fiction'),
NON_FICTION = Category.new(2, 'Non Fiction'),
CONTUTERS = Category.new(3, 'Contuters'),
]
CATEGORIES_BY_ID = ALL.index_by(&:id)
def initialize(id, name)
@id = id
@name = name
end
end
class BookCategory < ActiveRecord::Base
def category
Category::CATEGORIES_BY_ID[category_id]
end
end
class Book < ActiveRecord::Base
has_many :book_categories, :autosave => true
def categories
book_categories.map(&:category)
end
def category_ids
book_categories.map(&:category_id)
end
def category_ids=(ids)
ids = ids.reject(&:blank?)
book_categories.each do |book_category|
book_category.mark_for_destruction unless ids.include?(book_category.id)
end
(ids - category_ids).each do |new_id|
book_categories.build(category_id: new_id)
end
end
end