Rails Controllers

Continued from Rails 101

Opening up app/controllers/posts_controller.rb shows;

  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }

Post.all gets all posts which have been saved to the DB, and stored in the @posts variable. All variables within a ‘def’ (method) are available to the view

Rails 101

Create app (named blog);

$rails new <app name>
$rails new blog

Create database;

$rake db:create

Fire up the rails server

rails server

Generate index (home) page & remove the temporary pre-built page

$rails generate controller home index
$rm public/index.html

Generate resource (modal) – representing a single object – eg. Car / Post / House

$rails generate scaffold <Modal name> <fields>
$rails generate scaffold Post name:string title:string content:text

Do the DB Migration

$rake db:migrate

Rails Console;

$rails console
p = Post.new(:title => "abcd")
(expecting not to save)
Show the errors created
p.title = "abcdefg"
(expecting false - aka not saved)
Show errors


Routes file is: config/routes.rb
Views: app/views
Controllers: app/controllers
DB Migrations db/migrate/<datestamp>_create_<modal name>.rb

Thanks to: http://guides.rubyonrails.org/getting_started.html#getting-up-and-running-quickly-with-scaffolding