2

I am using this method for search engine friendly URLs in Rails - http://jroller.com/obie/entry/seo_optimization_of_urls_in

My model looks like this.

class Listing < ActiveRecord::Base
  def to_param
    "#{id}-#{title.parameterize}"
  end
end

This works with MySQL but not Postgresql.

This is the error I get:

ActiveRecord::StatementInvalid (PGError: ERROR: invalid input syntax for integer: "16- college-station-apartments" : SELECT * FROM "floorplans" WHERE ("floorplans"."listing_id" = E'16-college-station-apartments') ORDER BY beds ASC, baths ASC, footage ASC, price ASC):

Is ActiveRecord not doing a .to_i on the find for Postgresql?

Jared Brown
  • 1,949
  • 4
  • 20
  • 28
  • im not sure the problem is in the code you have posted ... maybe in your controller or migration ... anyway , for managing slugs i will suggest you to try friendly_id gem or stringex. have a look – andrea Feb 25 '11 at 23:02

1 Answers1

4

Rails will automatically call to_i on your parameter for some methods, mainly those where an integer is expected as a parameter, like Listing.find(params[:id]).

However, for other types of search methods that can accept strings as parameters, you'll need to manually call to_i

Listing.find_by_id(params[:id].to_i)
Listing.find(:conditions => ["id = ?", params[:id].to_i])

The reason you're not having a problem with MySQL is that MySQL does what would in effect be a to_i on its end (i.e. it's not a database-adapter issue, but rather a capability of the actual database server).

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • I think this is incorrect; I had a controller call find(params[:id]) and got the same error with a user-entered URL. There's no .to_i anywhere in 3.0.9's ActiveRecord finder_methods.rb. Maybe Rails used to do this, but no longer does, and nobody noticed because MySQL is so popular? – Jay Levitt Sep 21 '11 at 16:57