开发者

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

开发者 https://www.devze.com 2023-03-23 06:56 出处:网络
Given a model like Thread (id, uuid) uuid being a uniquely generated identifier. I want to change the default routes:

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=&开发者_StackOverflow中文版gt;"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


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.


:id can be changed to whatever you like. Your params hash gets populated by the name you choose in your routes, so if you changed it to :uuid you would just need to change your controllers accordingly (o = Model.find_by_uuid(params[:uuid]))

0

精彩评论

暂无评论...
验证码 换一张
取 消