1

I want to look up an object from the database using a GET with a parameter other than :id using a generated controller.

Currently when I GET /parties/8.json

{"id":8,"Name":"testname","Date":"5 July, 2015","Location":"testlocation","Requirements":null,"Password":"","URL":"WMKQUBBC","Token":"testtoken","created_at":"2015-07-05T23:45:22.474Z","updated_at":"2015-07-05T23:45:30.293Z"}

I want to be able to GET /parties/WMKQUBBC.json and get the same response, but it currently looks up only by :id.

I tried adding it in routes.rb

get 'parties/:URL' => 'parties#show'
resources :parties

to work with my parties_controller.rb

# GET /parties/1
# GET /parties/1.json
def show
  @party = Party.find_by_URL(:URL)
  format.html { redirect_to @party }
  format.json { render :show, location: @party }
end

but I still get a ActiveRecord::RecordNotFound exception, it seems like the action is defaulting to the standard Rails behavior for parties#show and it isn't even hitting my Party.find_by_URL(:URL) code.

Any ideas?

  • Which version of `Rails` you are using? – Pavan Jul 06 '15 at 02:34
  • You don't have another method below named `show` that handles fetching records with `id` right ? If there is one, even if the route is matched properly, that `show` method will be called resulting in a `RecordNotFound` error (id = nil). – limekin Jul 06 '15 at 02:44
  • I am using rails 4.2.1 and no I don't have another show method. I ended up finding a solution with this SO post: https://stackoverflow.com/questions/24226378/rails-routes-with-name-instead-of-id-url-parameters I used a gem called friendly_id. I'll add an answer soon. – Misha Griffiths-Prasolova Jul 06 '15 at 02:53
  • 2
    As you are using rails 4.2.1, change this `@party = Party.find_by_URL(:URL)` to `@party = Party.find_by(URL: params[:URL])` and check. – Pavan Jul 06 '15 at 02:59
  • Is my suggestion worked? – Pavan Jul 06 '15 at 07:08
  • @Pavan I solved it using the answer I linked previously with the ``friendly_id`` gem, but your method seems more elegant – Misha Griffiths-Prasolova Jul 06 '15 at 07:12
  • Did it worked with my suggestion? – Pavan Jul 06 '15 at 07:13

0 Answers0