user3576036
user3576036

Reputation: 1425

Setting default value of a column while generating active record model

I am trying to add devise authentication to my app. There will be two types of users, admin and public user. I am trying to achieve this by adding a boolean admin column to the User model that I am about to generate by doing,

rails g devise User admin:boolean 

How can I set the default boolean value to false here?

Upvotes: 3

Views: 3866

Answers (2)

Zia Qamar
Zia Qamar

Reputation: 1775

Best practice is to do it via migration

rails generate migration add_admin_to_users admin:boolean

It will generate migration for you and then add default: false:

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

And then rails db:migrate

And the answer of your question

Q: Setting default value of a column while generating active record model

Ans: You cannot pass default value to rails generate migration

Upvotes: 3

MrShemek
MrShemek

Reputation: 2483

Start with:

rails g devise User

Then open migration generated by the Devise and add:

t.boolean :admin, default: false

somewhere inside

create_table :users do |t|
  <here goes your code>
end

Upvotes: 5

Related Questions