2014-02-27 56 views
0

我正在創建一個rails應用程序,我無法弄清楚或找到這個問題的答案。Rails 3:如何編碼路徑路徑

什麼是路徑:

@example = Example.find_by_notId(params[:notId])

我希望我的路線更好看,然後/例子/ 1,寧願把它讀/ notId(其中notId將標題或其他一些非ID int)。通常我會使用show_path,但在我的HTML <%= link_to image_tag(pic), show_path(example) %>不起作用。這是我的代碼,它在我將其硬編碼到URL(localhost:3000/notId)中時起作用,但我需要通過鏈接路由它。有任何想法嗎?

顯示

def show 
    @example = Example.find_by_title(params[:title]) 
end 

路線

match '/:notId', to: 'example#show', via: 'get' 

_example.html.erb

<div class="example"> 
<% Movie.all.each do |example| %> 
    <%pic = example.title + ".jpg"%> 
    <%= link_to image_tag(pic), show_path(example) %> 
<% end %> 
e</div> 

回答

0

你可能需要重寫:id PARAM在你的路由:

resources :examples, param: :title 

這會產生這樣的路線:

/examples/:title 
/examples/:title/edit 

然後在您的觀點:

example_path(example.title) 

或者,您可以更改方法to_param(用於建立URL)的模型中:

class Example < ActiveRecord::Base 
    def to_param 
    title 
    end 
end 

這可以讓你繼續使用example_path(example)(不含.title

+0

謝謝你的工作,我只好把我的html改成'example_path(example.title)' – tzamzow

+0

對,我會用這一點編輯答案。 – markets