Search code examples
ruby-on-railsfriendly-id

Friendly_id PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer:


I try to use Friendly_id but I have an error just for one model.

track model :

class Track < ApplicationRecord 
  extend FriendlyId
  friendly_id :track_name, use: :slugged
  has_many :pois

poi model :

class Poi < ApplicationRecord
  extend FriendlyId
  friendly_id :name_and_city, use: :slugged
  belongs_to :track

I need to have a pois list by track

In my pois_controller :

def index
  @pois = Poi.all
  @pois = Poi.where("track_id = ?", params[:track_id])

In my routes :

 resources :tracks, only:[], :shallow => true  do
   resources :pois
 end

But I want to go to my pois_index, the params for track_id is a string (the slug), not an integer.

What can I do ?


Solution

  • In Rails bad idea to interpolate params into raw SQL. That is why you have an error with wrong syntax. In this case you should use ActiveRecord.

    Poi.where(track_id: params[:track_id])
    

    When you interpolate params to sql you should prevent sql injection. ActiveRecord do it automatically.