Hemant Bhargava
Hemant Bhargava

Reputation: 3585

habtm confusion.. Logical query

I have a Book model and status of the book can be anything from NEW, OLD, VERY_OLD. It can be NEW, OLD both or it could be both OLD and VERY_OLD. I want to save user choices in a database. How would you suggest I implement this?

I could create a new model for Book condition but I feel that there must be a better way.

Upvotes: 0

Views: 43

Answers (1)

GMA
GMA

Reputation: 6096

If I understand your question right, there are five possibilities for a book's status:

  1. NEW
  2. OLD
  3. VERY_OLD
  4. NEW & OLD
  5. OLD & VERY_OLD

Assuming I've got that right, you could accomplish this with an ActiveRecord::Enum. This would only require to add one new column to your DB, and wouldn't require a new model.

First add a status column if you haven't already got one:

# In a migration
add_column :books, :status, :integer
add_index :books, :status

(You might also want to add null: false to the line add_column, if you don't want it to be possible for a book to have no status.)

Then add this to your Book model:

class Book < ActiveRecord::Base

  enum status: [:new, :old, :very_old, :new_and_old, :old_and_very_old]

end

This generates methods on Book called new?, old?, very_old? etc. You might want to override these e.g. so new? returns true if status is new_and_old as well as just new:

def new?
  status == "new" || status == "new_and_old"
end

Another way to do this could be to add boolean columns to book called new, old, and very_old, but then this would require you to add a bunch of validations (e.g. to make sure that a book can't be both "new" and "very old".)

Upvotes: 3

Related Questions