vendredi 20 novembre 2015

Move static data from db into code in rails 3

Let's say I have a simple scenario with 2 models, Books and Categorys, where each book has and belongs to many categories.

I want to move the Category data out of the database as per here and here.

My category class looks like this:

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

I have a books_categories table like this:

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

How should I model this in my book class, and in the db?

Ideally, I'd like it to look like this:

class Book < ActiveRecord::Base
  has_many :categories
end

But where the book can be added or removed from categories.

One approach would be to be to use embedded associations. The thing I don't like about this is that it makes the db hard to inspect.

Are there any other approaches, perhaps maintaining the existing books_categories table?

Aucun commentaire:

Enregistrer un commentaire