automatic type casting of query parameters in finds

I'm new to ruby on rails and am using active record 3 to create some object models on top of a postgres db.

I have an Environment record with a :name attribute that maps to the :name column of type :string. When I do Environment.find_by_name( "abc" ), everything works as expected. However, when I do Environment.find_by_name( 123 ), my code breaks with the following error:

ERROR: operator does not exist: character varying = integer (ActiveRecord::StatementInvalid) LINE 1: ...nts"."purpose" = 'test' AND "environments"."name" = 123) LI...                                                              ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

So my question is, if activerecord knows the type of the :name column (:string), then why doesn't it automatically call to_s on the :name parameter to avoid this issue?

I have a work around right now that overrides find, and explicitly does this type casting, but I'm guessing there is a cleaner way to achieve this behavior.

Thanks, Alex

1 Like