3

Is there any way to get the real id column from a model that is modified with friendly_id?

I don`t want to make another db query for it, in performance reasons.

M2_
  • 217
  • 4
  • 14

2 Answers2

5

Broadly speaking friendly_id modifies to_param and find methods. Next should work:

@affiche = Affiche.find(params[:id]) # params[:id] is a slug
@id = @affiche.id
Voldy
  • 12,829
  • 8
  • 51
  • 67
0

Have you tried attributes["id"]? e.g: Model.first.attributes["id"]

Mattias Wadman
  • 11,172
  • 2
  • 42
  • 57
  • I don\`t really get where to use it. But if I'll do in controller `@id = Affiche.first.attributes["id"]` I get nothing – M2_ Oct 30 '11 at 13:22
  • Do you get `nil`? if the database query triggered by running `first` includes the `id` column i think you should be able to access it via the attributes hash. But i don't know how the friendly_id plugin works, looks like it uses a separate table for all slugs. So i guess @voldy answer should work. – Mattias Wadman Oct 30 '11 at 14:15
  • but again it is one more query, isn't there another way? Something like modifying model, maybe, to add the real `id` to `params`. Or somehow pasing the real `id` through the slug? And slugs are in the same table as `id`s for `frienly_url` – M2_ Oct 30 '11 at 15:06
  • I meant that you should be able to use `attributes` on the model instance you already have. How do you look up the model instance in the first place when using the friendly id? – Mattias Wadman Oct 30 '11 at 15:19