views:

14

answers:

1

I'm testing Rails 3 beta 4 on Ruby 1.9.2-head, and when I start a console and do:

Game.first.to_sql

I get this error:

ArgumentError: wrong number of arguments (0 for 1)

I know it can find the Game record, because when I type:

Game.first

it returns:

=> #<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37",
updated_at: "2010-06-19 11:02:37">

What am I missing? I just want to make the to_sql work in a very simple case.

.

+2  A: 

When you run Game.first you are returning a Game object, not a ActiveRecord::Relation object as you are expecting.

To do what you're trying to do, you'll need to do:

Game.limit(1).to_sql

This lets you run it without to_sql and return the object as you expected it, although it will be in an array, which then you can run .first on it like you wanted anyways.

irb(main):004:0> Game.limit(1).to_sql
=> "SELECT `games`.* FROM `games` LIMIT 1"
irb(main):005:0> Game.limit(1).class
=> ActiveRecord::Relation
irb(main):006:0> Game.limit(1)
=> [#<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37", updated_at: "2010-06-19 11:02:37">]
irb(main):007:0> Game.limit(1).first
=> #<Game id: 1, name: "Galaga", created_at: "2010-06-19 11:02:37", updated_at: "2010-06-19 11:02:37">

When you dig into the source, when you run .first on an ActiveRecord::Relation it runs the following (which is the same as I showed you):

def find_first
  if loaded?
    @records.first
  else
    @first ||= limit(1).to_a[0]
  end
end
Garrett
It works! I was affraid that my dev machine was not setup correctly with Rails or Ruby. Like some module was missing or something. I see not that I was just doing it wrong.Now I've got to get my head around the differences between a query definition and the model that comes from it. I'll get there. Thanks for the help.
MattSlay