简体   繁体   English

为什么Rails中的:id在Postgresql中不起作用,但在MySQL中却起作用?

[英]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 我在Rails中将这种方法用于搜索引擎友好的URL- 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. 这适用于MySQL,但不适用于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): ActiveRecord :: StatementInvalid(PGError:错误:整数的无效输入语法:“ 16- College-Station-apartments”:SELECT * FROM“ floorplans” WHERE(“ floorplans”。“ listing_id” = E'16-college-station-apartments ')ORDER BY床ASC,浴室ASC,镜头ASC,价格ASC):

Is ActiveRecord not doing a .to_i on the find for Postgresql? ActiveRecord是否在Postgresql的查找中不执行.to_i?

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]) . Rails会针对某些方法自动在参数上调用to_i ,主要是那些期望将整数作为参数的方法,例如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 但是,对于可以接受字符串作为参数的其他类型的搜索方法,您需要手动调用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). 您对MySQL没问题的原因是MySQL to_i在其末尾执行了to_i (即,这不是数据库适配器问题,而是实际数据库服务器的功能)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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