user3800827
user3800827

Reputation: 13

Rails: MySQL2 Error when hitting the finder of a model

with Rails I hit this:

User.find(:all, :conditions => ["character = ?", character])

character is a Fixnum, as you can see by the way it is translated for the sql. A Fixnum is expected.

Then I get this error:

Mysql2::Error: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near '= 5)'
at line 1: SELECT `users`.* FROM `users` WHERE (character = 5)

I'm somewhat confused and absolutely do not get what might be wrong with this line of sql.

Please help.

Yours

Joern

Upvotes: 1

Views: 53

Answers (2)

Max Williams
Max Williams

Reputation: 32955

The problem is that character is a keyword in mysql. If you escape it in backticks it should work, eg

User.find(:all, :conditions => ["`character` = ?", character])

When you do a rails find like

User.where(:character => character)

as Rich Peck suggests, then rails automatically escapes the names of all fields to prevent this problem: you can see it do this in your log.

EDIT: you might find it less hassle in the long run to change the name of your column.

Upvotes: 1

Richard Peck
Richard Peck

Reputation: 76784

ActiveRecord

If using Rails 4, you should use this to look up multiple records:

User.where character: character

If you want to load a specific record, you can just use .find like this:

User.find_by character: character

--

Specific

I think your error is more an ActiveRecord issue than a Fixnum one - the fact you're using that data to look up the records shouldn't have any bearing.

I could be wrong, but I think the bottom line is your use of the ActiveRecord methods you've defined.

Upvotes: 0

Related Questions