开发者

Rails: Using to_param for SEO-friendly slugs screwing up database calls?

So in my Rails models I'm doing the following to generate an "SEO friendly" slug:

def to_param
  "#{id}-#{title.parameterize}"
end

So that generates something 开发者_JAVA技巧like: example.com/items/1-example-title

But when I check my logs, the SQL calls are then:

SELECT * FROM `items` WHERE (`items`.`id` = '1-example-title') LIMIT 1

That seems to work fine for MySQL, but PostgreSQL flips out on it.

So, how can I get my SQL query to just use 1 for the id instead of the full slug?


Make sure you are using the standard find call.

Model.find(params[:id])

If you use alternative syntaxes, such as

Model.find_by_id(params[:id])
Model.first(:conditions => { :id => params[:id] })

then you need to cast the parameter to integer.

params[:id].to_i
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜