[英]Rails 3: how to code a route path
我正在创建一个Rails应用程序,但找不到或找不到该问题的答案。
路线是:
@example = Example.find_by_notId(params[:notId])
我希望我的路线比/ example / 1更好,并希望将其读为/ notId(其中notId将是title或其他一些非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>
您可能需要在路由中覆盖:id
参数:
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
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.