0

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 ?

Ben
  • 660
  • 5
  • 25
  • If you need the `track_id` to be an integer, why not just convert it? `params[:track_id].to_i`. Also, you don't need the `.all` query. – vich May 12 '18 at 17:40
  • Because in params I have the track slug and not the track id – Ben May 12 '18 at 20:11

1 Answers1

0

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.

  • 1
    Maybe... but the problem it's not here. I get the slug not the id. Parameters: {"locale"=>"en", "track_id"=>"variante"} Poi Load (0.5ms) SELECT "pois".* FROM "pois" WHERE "pois"."track_id" = $1 [["track_id", 0]] – Ben May 12 '18 at 23:31
  • I see rails console and when I try `User.where('id = ?', 'asd')` I have error `ActiveRecord::StatementInvalid: PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "asd"` When I do `User.where(id: 'asd')` I have `#` So your error said about wrong parameter interpolation. – Artem Dorodovskyi May 12 '18 at 23:37
  • It's true. Thks I do not have any more this error but my list stay empty. :( – Ben May 12 '18 at 23:46
  • You can find pois by track slug. If find tracks and then find pois. `tracks = Track.friendly.find(params[:track_id]); @pois = Poi.where(track_id: tracks)` according to the [guide](http://norman.github.io/friendly_id/file.Guide.html) of FriendlyId – Artem Dorodovskyi May 12 '18 at 23:52
  • Friendly gem just add `friendly.find` method for ActiveRelation or ActiveRecord. So you can use only this method for finding by slug and then use ActiveRecord. – Artem Dorodovskyi May 13 '18 at 00:01
  • Thanks a lot Artem for your help ;) All work fine now. – Ben May 13 '18 at 12:56