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

独自空忆成欢 提交于 2020-01-15 08:42:16

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/5122762/why-does-this-id-in-rails-not-work-with-postgresql-but-it-does-work-with-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!