开发者

Activerecord can't find model by attribute, even though the query is correct

I have a Model called Invitation which has an attribute called code. The application's goal is to find the correct invitation with a code that is entered somewhere.

My problem is, however, that even though the input is correct, ActiveRecord can't seem to find any results while querying in the datab开发者_如何学Pythonase. I've created this small test to illustrate the problem:

ruby-1.9.2-p290 :003 > code = Invitation.first.code
Invitation Load (0.4ms)  SELECT "invitations".* FROM "invitations" LIMIT 1
=> "86f50776bf" 

So at this point I've loaded this invitation's code in a variable

ruby-1.9.2-p290 :004 > i = Invitation.where(:code => code)
Invitation Load (0.2ms)  SELECT "invitations".* FROM "invitations" WHERE "invitations"."code" = '86f50776bf'
=> [] 

And the response of the query is an empty array, even though the code comes straight from the database. When using code == Invitation.first.code to see if the values are equal, it returns true. I already checked both the Ruby and database's data types, they're all Strings.

What can cause this? and how can I fix this?


Based on your comment, it could be the case that the column is not VARCHAR but CHAR, or it contains trailing spaces that are being trimmed off by the ActiveRecord ORM layer or the database driver. 'foo' and 'foo ' are not equivalent, but they are LIKE enough to match.

You may want to switch that column to variable length, or to adjust your query to test: RTRIM(code)=?


I found the solution when I stumbled upon this answer:

In Ruby 1.9, all strings are now encoded. By default, all strings should be UTF-8, however, SecureRandom.hex(30) returns an encoding of ASCII-8BIT.

Adding .force_encoding('UTF-8') to the key when it's being executed solves the problem :)


@Marco,

How you declare the code variable? As String?

Example:

code = "86f50776bf"

or

code = '86f50776bf'

?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜