2014-02-27 53 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