Rails Scaffolding SyntaxError

November 13th, 2012.

Rails 3.2.8 scaffolding and the error

Last night while going through the first lesson in the Ruby on Rails guide at rubyonrails.org I came across a bizarre error. All I had done, at this point, was connect to a database (SQLite3) and run the following scaffold command as per the tutorial:


rails generate scaffold Post name:string title:string content:text

When I looked at my http://localhost:4000/posts/ page there were a number of syntax errors. Most of them had to do with the way collections (at least that’s what I think it is) are written. Here is a sample of one of the errors


/projects/blog/app/controllers/posts_controller.rb:9: syntax error, unexpected ':', expecting '}'
format.json { render json: @posts }
                          ^

expand

What the heck? I hadn’t even written any code of my own at this point!

In my posts_controller.rb file:


class PostsController < ApplicationController
  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end
...(continued. This was all generated via a scaffold.)

expand

My ruby -v said ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin12.2.0]

I always got that SyntaxError message, even after trying different versions of Ruby (using rbenv). I tried switching to version 1.9.2-p290, 1.9.2-p320, and 1.9.3-p194… the preferred version of Ruby that Rails 3.2.8 recommends. How could the code generated by the Rails 3.2.8 scaffolding be syntactically outdated?

I posted the question on StackOverflow as best as I could describe it, battled it for another hour, and went to bed frustrated.

Solution

By noon the next day, someone suggested this:

In your Gemfile specify the ruby version like so ruby ‘1.9.3’ right under the sources.

So, I added this second line to the top of my Gemfile:


source 'https://rubygems.org'
ruby '1.9.3'

That did the trick. For some reason, even though ruby -v returned ruby 1.9.3p194, I still needed to specify that this project requires ruby 1.9.3 in my gemfile. There’s some sort of bug there, either with rbenv or with my particular environment.

I’m just glad it’s fixed and I can press on learning.