Leonardo
Leonardo

Reputation: 228

How to add a new attribute to a model (ActiveRecord) in Ruby

I'm new on Ruby on Rails and I'm simply trying to add a new attribute to an existing model. I have to add a new boolean attribute to my class that inherits from:

ActiveRecord::Base

Would someone explain, step by step, how to do it?

Upvotes: 0

Views: 4035

Answers (3)

Camilo Camargo
Camilo Camargo

Reputation: 61

Only you need to add a new migration file to make changes to the database.

rails g migration AddFieldToMyTable my_field:string

Now, you need to persist the change:

bundle exec rake db:migrate

If you want to add the field to the form, do not forget to add the new field in the attributes accepted by the controller:

def model_params
  params.require(:model).permit(...., :my_field)
end

Simple explained that is the process, I hope it has helped you! (Google traductor love :[)

Upvotes: 1

Mark
Mark

Reputation: 6455

You need to use migrations in order to add fields to a database. The easiest way to create these files is with a terminal command, however they can be created manually:

http://edgeguides.rubyonrails.org/active_record_migrations.html

Every time you add a migration, you will need to apply it to your database, which is done with:

rake db:migrate

When you run this, rails go through all your migration files checks which have been applied, and then runs through the rest in order. This means you can roll back migrations that you've screwed up, and can look at the database in different 'stages' of migration if needed.

In your case, we want to add say a field of 'published' to our model 'Book'. We would run from terminal:

rails g migration addPublishedToBook published:boolean

You can see the structure from above. If we wanted to add a string called firstname to our model User:

rails g migration addFirstnameToUser firstname:string

After you run these tasks from terminal, each one will create a new migration file. When you're ready, run rake db:migrate, and the new changes will be applied to your database.

Upvotes: 3

Sebastián Palma
Sebastián Palma

Reputation: 33471

You can generate a new migration specifying the attribute and model which it corresponds:

$ rails generate migration add_new_attribute_to_model new_attribute:type

This will generate a migration like:

class AddNewAttributeToModel < ActiveRecord::Migration[RailsVersion]
  def change
    add_column :model, :new_attribute, :boolean # boolean type attribute
  end
end

Then you can persist the changes:

$ rails db:migrate

Upvotes: 2

Related Questions