Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

routes.rb, how set a different primary key for the paths?

Given a model like Thread (id, uuid) uuid being a uniquely generated identifier. I want to change the default routes:

edit_thread GET    /threads/:id/edit(.:format)                        {:action=>"edit", :controller=>"threads"}
thread GET    /threads/:id(.:format)                             {:action=>"show", :controller=>"threads"}
PUT    /threads/:id(.:format)                             {:action=>"update", :controller=>"threads"}

To not use :id but to user :uuid --- How is this made possible in Rails/routes.rb?

Thanks

like image 573
AnApprentice Avatar asked Jul 26 '11 20:07

AnApprentice


People also ask

How do routes work in Ruby on Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

What is match in Rails routes?

Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.

What is namespace in Rails routes?

In a way, namespace is a shorthand for writing a scope with all three options being set to the same value.


1 Answers

If I understand correctly, you want to make sure instead of the :id field, Rails uses the :uuid field in the routes.

This is quite easy to accomplish, inside your model overrule the to_param method:

def Thread
  def to_param
    uuid
  end
end

and inside your controller, you will have to write something like:

thread = Thread.find_by_uuid(params[:id])

Hope this helps.

like image 93
nathanvda Avatar answered Oct 09 '22 14:10

nathanvda