简体   繁体   中英

Why does this :id in Rails not work with Postgresql but it does work with MySQL?

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?

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 (ie it's not a database-adapter issue, but rather a capability of the actual database server).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM