My Rails 3 app has a UserAction object that I use to store information about actions taken on my site.
I’m trying to filter the results so that I only get ones where the data attribute is set to a specific value, but for some reason it always returns an empty array.
Here’s an example from the console showing the first record, a query that returns it based on the ‘action’ attribute, and the one that’s not working for the ‘data’ attribute:
> UserAction.first
UserAction Load (39.6ms) SELECT "user_actions".* FROM "user_actions" LIMIT 1
=> #<UserAction id: 1, source: "127.0.0.1", action: "Failed login attempt", data: "admin", created_at: "2012-01-12 11:26:38", updated_at: "2012-01-12 11:26:38">
> UserAction.where('action = ?', "Failed login attempt")
UserAction Load (1.2ms) SELECT "user_actions".* FROM "user_actions" WHERE (action = 'Failed login attempt')
=> [#<UserAction id: 1, source: "127.0.0.1", action: "Failed login attempt", data: "admin", created_at: "2012-01-12 11:26:38", updated_at: "2012-01-12 11:26:38">]
> UserAction.where('data = ?', "admin")
UserAction Load (96.5ms) SELECT "user_actions".* FROM "user_actions" WHERE (data = 'admin')
=> []
Why does Rails return an empty array for the second query when there’s clearly a record where the data equals “admin”? I should note that I’m currently upgrading the app from Rails 2.3.5, so it might be something new introduced in Rails 3 (I am using Rails 3.1.2). Also, I’ve started using Postgresql in development instead of Sqlite, which I was using before.
Thanks in advance.
I figured out the answer (kind of):
The data parameter was serialized and for some reason when Rails 3’s ActiveRecord deserializes a string, it doesn’t equal the string you search for with your query.
I removed the serialize and it worked.