routes.rb,如何为路径设置不同的主键?

AnA*_*ice 8 ruby ruby-on-rails ruby-on-rails-3

给定像Thread(id,uuid)这样的模型uuid是唯一生成的标识符.我想更改默认路由:

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"}
Run Code Online (Sandbox Code Playgroud)

不使用:id但是对用户:uuid ---如何在Rails/routes.rb中实现这一点?

谢谢

nat*_*vda 7

如果我理解正确,你想确保代替:id字段,Rails使用:uuid路由中的字段.

这很容易实现,在你的模型中否决了to_param方法:

def Thread
  def to_param
    uuid
  end
end
Run Code Online (Sandbox Code Playgroud)

在你的控制器里面,你必须写下这样的东西:

thread = Thread.find_by_uuid(params[:id])
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


cam*_*cam -1

:id可以更改为您喜欢的任何内容。您的params哈希值将由您在路由中选择的名称填充,因此,如果您将其更改为,:uuid您只需要相应地更改您的控制器(o = Model.find_by_uuid(params[:uuid])