将数据库中的静态数据移动到 rails 中的代码中 3

Move static data from db into code in rails 3

假设我有一个简单的场景,有 2 个模型,Books 和 Categorys,其中每本书都属于许多类别。

我想按照 here and here.

Category 数据移出数据库

我的类别 class 如下所示:

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 table 这样的:

| book_id | category_id |
| 1       | 1           |
| 2       | 3           |
| 3       | 1           |
| 3       | 2           |
...

我应该如何在我的书 class 和数据库中对此进行建模?

理想情况下,我希望它看起来像这样:

class Book < ActiveRecord::Base
  has_many :categories
end

但是可以在类别中添加或删除图书的位置。

一种方法是使用 embedded associations。我不喜欢的是它使数据库难以检查。

是否有任何其他方法,也许可以维持现有的 books_categories table?

我查看了 https://github.com/pboling/flag_shih_tzu,但最后,我用一个简单的 has_many 连接模型实现了它。我在 books_categories table 中添加了一个 id 列,重命名为 book_categories 并在 Book:

上实现了自定义 getters/setters
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