Archive

Archive for the ‘Announcements’ Category

Quick live code from Sunday Section

December 13th, 2009 Jonathan No comments

Attached is the quick and dirty multiple model form from today’s section.

Click here to download.

Categories: Announcements Tags:

Simple Form / Partial Example

November 8th, 2009 Jonathan No comments

Another completed project from the Sunday section.

This application makes use of the following:

  • form_for
  • Partials for DRYness
  • has_many :through where tables and foreign keys don’t match
  • collection_select drop downs
  • named_scope and default_scope

Click here to download the completed application.

Categories: Announcements Tags:

Nice book chapter on REST

November 1st, 2009 john No comments

I think I’ve recommended this book before: Eldon Alameda’s Practical Rails Projects.

It has a sweet chapter on building a RESTful application, and shows very well how the controllers should be “rescoped” to work only on data that is appropriate. This “rescoping” is part of the requirements for Assignment 4 (requirement #5 about not letting users edit data “owned” by another user).

That chapter is a free download:

http://www.apress.com/book/view/1590597818

Categories: Announcements, Rails Tags:

Assignment 4 download available

October 31st, 2009 john No comments

For those of you who burn the midnight oil, as I do . . .

The download for Assignment 4 (and 5) is available on the downloads page. I’ll send an e-mail tomorrow morning (the Harvard e-mail service is unavailable from 1 AM to 4 AM!!).

Categories: Announcements Tags:

What gets validated?

October 26th, 2009 Antony No comments

Say you have a model called Match with attributes wins and losses, both of type integer.  To this model you add validation to ensure these attributes are only integers:

class Match < ActiveRecord::Base
 validates_numericality_of :wins, :only_integer => true
 validates_numericality_of :losses, :only_integer => true
end

Then, in script/console:

>> m = Match.new
=> #<Match id: nil, wins: nil, losses: nil, created_at: nil, updated_at: nil>
>> m.wins = "seven"
=> "seven"
>> m.losses = "five"
=> "five"
>> m
=> #<Match id: nil, wins: 0, losses: 0, created_at: nil, updated_at: nil>
>> m.valid?
=> false

The strings have been cast as integers, but why does the validation fail?  The answer is that ActiveRecord stores much more information than what shows up as instance attributes.

>> m.attributes_before_type_cast
=> {"created_at"=>nil, "losses"=>"five", "updated_at"=>nil, "wins"=>"seven"}

An indepth look at all of the machinery of ActiveRecord might be a course in itself, but I thought this would provide a taste of the breadth and depth of the ORM.

Categories: Announcements Tags:

Migrating existing data

October 26th, 2009 Antony 2 comments

Agile Web Development with Rails, 17.4 and 17.5, covers this subject.

On page 307 of the PDF, Migrating Data with Migrations, the basic scheme you might use is demonstrated.  As another example, suppose I create a users table and model:

$ ./script/generate model users first_name:string last_name:string

The migration looks like this:

class CreateUsers < ActiveRecord::Migration
 def self.up
   create_table :users do |t|
     t.string :first_name
     t.string :last_name

     t.timestamps
   end
 end

 def self.down
   drop_table :users
 end
end

After adding a number of users, it becomes clear that a full_name attribute would be very useful:

$ ./script/generate migration AddFullNameToUser full_name:string

This new migrations looks like this:

class AddFullNameToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :full_name, :string
  end

  def self.down
    remove_column :users, :full_name
  end
end

Before running it, I add the line to update the users:

class AddFullNameToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :full_name, :string
    User.find(:all).each do |u|
      u.full_name = u.first_name + ' ' + u.last_name
      u.save!
    end
  end

  def self.down
    remove_column :users, :full_name
  end
end

An important note here:  I did not use update_all because string concatenation is not portable between database engines (|| for Oracle, postgres and sqlite3, + for SQL Server and Sybase,  concat for MySQL, etc).

As John demonstrated in his migrations 3 example, depending on what you are trying to accomplish, the down method may not be data preserving.

Beyond the above and similar data manipulation, section 17.5 covers ways to execute fragments of native SQL or arbitrary SQL.  Using this functionality is beyond the scope of this course and of course has the significant downside of being much less portable.

Categories: Announcements Tags:

Additional Standalone ActiveRecord Example

October 11th, 2009 Jonathan No comments

In the Sunday section, we re-created the previous example application using ActiveRecord. This is very similar to the examples from Lecture 6 in the download section, except that this was written with an emphasis on test driven development.

It includes examples of:

  • Migrations
  • Simple Seed Data
  • Fancy Finders
  • Validations and Validation Testing
  • One to Many Relationships

For the sake of time, there were no many to many relationships. Examples of m2m can be found in the download section.

Use rake -T to view the rake tasks. Use “rake db:migrate” to run the migrations, and “rake test” to run the tests.

Run “ruby section.rb” to run the demo code. Modify section.rb to play around with the finished results.

You can click here to download the complete source code.

Categories: Announcements Tags:

Command line sqlite

October 10th, 2009 Antony 6 comments

Execute the command sqlite3 at the command prompt passing the file name of the database:

$ sqlite3 <database name>.sqlite3

You should see output similar to the following:

SQLite version 3.6.10
Enter “.help” for instructions
Enter SQL statements terminated with a “;”
sqlite>

Check that the version is correct.  People running sqlite3 in emacs may need to set sql-sqlite-program.

Enter ‘.help’ to see the list of commands that provide information or set options. Input starting with a ‘.’ (period) signals non-SQL and should be one of those commands.  All other input will be interpreted as SQL and should be terminated with a ‘;’ (semi-colon).

Enter ‘.quit’ to exit.  Some other commands you will likely find useful are ‘.headers’, ‘.tables’, and ‘.schema’.

When using rails with sqlite3, this same functionality can be started with ’script/dbconsole’.

Categories: Announcements Tags:

Best Books on Rails

October 7th, 2009 john No comments

Compared to Ruby, the pickings are slim for great books that try to explain core Rails from end-to-end. Generally, each good book on Rails approaches a part of the Rails elephant.

Here are the ones I recommend:

Ruby, Thomas, and Hansson, Agile Web Development with Rails, 3d ed. (Amazon). If you’re taking this course, you should own this already. AWDR touches all the bases, but still has sections that drive readers a little bit crazy. But . . . essential.

David Griffiths, Head First Rails (Amazon; Safari). If you’re a learn-by-doing person and have the time to work through a book, this is the one. The Head First books know a lot about triggering learning in your brain through exercises and pictures. I think this book is most worthwhile very early in your experience with Rails; afterwards it may feel redundant.

Eldon Alameda, Practical Rails Projects (Amazon). The examples in this book are real-world and slick. Almeda has a good way at demonstrating how quickly you can get stuff done with Rails, selected Gems, and Rails plugins. A lot of good stuff on integrating Ajax/JavaScript with Rails.

Brad Ediger, Advanced Rails (Amazon; Safari). The natural followup to AWDR for readers who really have to get it right. The best aspect of this book is that it dares to go into some depth on topics such as the database, security, and performance.

Dan Chak, Enterprise Rails (Amazon; Safari). The meat of this book is about leveraging the underlying power of your database, using features that are a bit out of the Rails mainstream (composite keys; views; triggers; etc.). The book also benefits from understanding from the get-go that your new shiny enterprise app should be exposing and consuming services (SOAP, REST).

Obie Fernandez, The Rails Way (Amazon; Safari). This book is a ginormous grab bag of real-world scar tissue on just about every Rails topic. Want to know how and when the Rails Class Loader runs? Check. Should RESTful resource be nested deeply? Check. What’s wrong with CookieStore? Check. To buy after completing two Rails applications.

Categories: Announcements, Resources Tags:

Download of Ruby 1.9 docs with Rails docs

October 2nd, 2009 john No comments

I know that Windows users are hampered because ri is not properly installed.

If you’d like a nicely-formatted download of Ruby and Rails docs, try http://railsapi.com/

You can customize what you want, and include other components, adding docs for, say, the popular Hpricot HTML/XML parsing library (and much else).

They package docs for Rails 2.3.4 (rather than 2.3.3, which we’re using) which should be fine.

For Rails, a student reminds me that you can run “gem server” in one window, and then browse to http://localhost:8808/ to see docs for all gems you’ve installed (but not the core/standard Ruby docs).

Categories: Announcements Tags: