0

So I have this model Request, that was working perfectly. I decided to add it a "status" field, with a default value

def change
    create_table :requests do |t|

        t.references :owner,     index: true
        t.references :pretender, index: true
        t.belongs_to :book,      index: true

        t.string :status, value: "pending", null: false

        t.timestamps null: false
    end
end

But now I get an COnSTRAINT NOT NULL on this line:

...
user.requests.build owner_id: oid, pretender_id: pid, book_id: bid
...

Which was working just fine. If the field has a default value, I shouldn't need to define it on the buildmethod, no?

2 Answers 2

3

In the migration file, the syntax is not value, it is default:

t.string :status, null: false, default: 'pending',
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that is embarassing... Thanks!
1

As MurifoX already has answered use the default option instead of value.

ActiveRecord has a really nice trick up its sleeve called enumerables. Basically you store the status as an integer:

t.integer :status, null: false, default: 0, index: true

And then in your model you add the values that the column maps to:

class Request < ActiveRecord::Base
  enum status: [:pending, :reserved, :foo, :bar]
end

This automatically gives you:

Request.reserved # scopes
request.pending? # interrogation methods
request.reserved! # bang methods to change the status.

Its also much faster to perform queries on the database based on the status since you are comparing integers instead of strings.

3 Comments

Now this is BADASS! I get the interrogation method and the bang method, but what does the first one do?
Oh, I see. You use the class name, not the instance! Cool! :D
The first one does Request.where(status: :reserved)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.