2011-07-26 32 views
8

給出一個像Thread(id,uuid)uuid這樣的模型,它是一個唯一生成的標識符。我想改變缺省路由:routes.rb,如何爲路徑設置不同的主鍵?

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"} 

要不要使用:ID,但用戶:UUID ---這是如何在軌道/ routes.rb中成爲可能?

感謝

回答

-1

:id可以改變任何你喜歡的。你params哈希得到由你在你的路由選擇的名稱填充,所以如果你把它改成:uuid你只需要相應地改變你的控制器(o = Model.find_by_uuid(params[:uuid])

+0

謝謝,但我沒有得到的是如何改變它在我的路線?我需要做一堆比賽嗎?我想軌道會有一個更優雅的設置... thxs – AnApprentice

+1

@AnApprentice:對不起,我沒有意識到你的意思是你想改變資源路線中的'id'參數。我不認爲這是可能的(你在這裏突破軌道公約)。之前有人問過類似的問題:(http://stackoverflow.com/questions/810385/how-to-rename-the-default-identifier-param-id-in-rails-map-resources)。 – cam

7

如果我理解正確的話,你要確保,而不是:id字段,Rails在路由中使用:uuid字段。

這是很容易做到,內部模型否決to_param方法:

def Thread 
    def to_param 
    uuid 
    end 
end 

和你的控制器中,你將不得不寫類似:

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

希望這有助於。

相關問題