Yannick Schall
Yannick Schall

Reputation: 34969

Rails 3: Update database and scaffold

I'm starting in the big wooly world of Ruby on Rails and i'm trying to get my head around scaffolds and models. (cue, I'm a designer)

I use the rails generate scaffold command

rails generate scaffold Lesson title:string description:text

But is it possible to update the Lesson table with new key, values with rails?

I tried:

rails generate model Lesson title:string description:text dtstart:datetime

But when I run the db:migrate it fails and the only way around I know of to do that is to delete all of the scaffold and regenerate it.

I'm sure there must be an easier solution :)

I think (but im not sure, that it is because of the db/development.sqlite3 file that is not updated, when I delete the content by hand it then run the bd:migrate) is there a way to have evrything updated at once?

Upvotes: 2

Views: 5211

Answers (2)

mariopolito69
mariopolito69

Reputation: 1

I think you must also update (in rails 5 at least) your lesson_params in lessons_controller.rb in order to allow the new parameters to be passed from the view to the model.

Upvotes: 0

MrTheWalrus
MrTheWalrus

Reputation: 9700

I don't think there is a way to do what you describe - generally if you want to add new fields to a model, you want to generate a migration:

rails g migration AddStartToLesson

Then open the migration file and add the code that will add those fields. It will probably end up looking something like this:

class AddStartToLesson < ActiveRecord::Migration
  def self.up
    add_column :lessons, :start, :datetime
  end

  def self.down
    remove_column :lessons, :start
  end
end

And you'll have to update some of the views - probably _form.html.erb, to get the form field to enter that data, and index.html.erb and show.html.erb to display it. (they're probably in app/views/lessons/)

Upvotes: 5

Related Questions