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

So, in Rails models, I do the following to create an “SEO-friendly” slug:

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

This creates something like: example.com/items/1-example-title

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

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

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

So, how can I make my SQL query just use 1for idinstead of a full pool?

+3
source share
1 answer

Make sure you use the standard search call.

Model.find(params[:id])

If you use alternative syntaxes like

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

then you need to specify the parameter in an integer.

params[:id].to_i
+5

Source: https://habr.com/ru/post/1737356/


All Articles