hwrdprkns
hwrdprkns

Reputation: 7585

Edit Rails Model From Command Line

I am pretty new to Ruby on Rails, and I was wondering if there was a way to edit the database schema for a model.

For example, I have the Subscriber model in my application -- the way I created it was by using rails generate scaffold Subscriber email:string

But now, I want a name in the subscriber model as well. Is there any easy way to do this? I have put a lot of code in my current controllers and views, so I don't necessarily want to destroy the scaffold, but I would like to edit the model.

Thanks in advance,

hwrd

P.S. I am using Ruby on Rails 3

Upvotes: 12

Views: 16628

Answers (2)

Josh Lindsey
Josh Lindsey

Reputation: 8793

An ActiveRecord Model inspects the table it represents. You don't actually need to change your model just to add a new field (unless you want to add validations, etc).

What you want to do is make a new migration and then migrate your database up:

rails g migration AddNameToSubscribers name:string
rake db:migrate

Then you can start referencing the name field in your controllers and views.

(This generator command might seem a little magical, but the rails generator recognizes this format and will generate the appropriate add_column and remove_column code. See the Rails migration guide for further reading.)

Upvotes: 15

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

If you mean changing the database schema of your model, you'll want to use migrations.

You'll do things like

add_column :city, :string
remove_column :boo

http://guides.rubyonrails.org/migrations.html

If you do only mean finding models and updating the data inside each instance, go with @apneadiving's answer.

Upvotes: 2

Related Questions