[英]Ruby on Rails - Couldn't find Post with 'id'=string
Having trouble passing a string as a parameter instead of an ID. 在传递字符串作为参数而不是ID时遇到麻烦。 I keep getting hit with "Couldn't find Post with 'id'=stack".
我一直受到“找不到'id'= stack的帖子”的打击。
routes.rb makes a GET request for a :short_url in the redirect controller. routes.rb在重定向控制器中对:short_url发出GET请求。
get '/:short_url' => 'posts#redirect'
resources :posts
post_controller.rb is finding the params[:short_url] of the in the post. post_controller.rb在帖子中找到的参数[:short_url]。
def redirect
@post = Post.find(params[:short_url])
redirect_to @post.(params[:url])
end
The view is simply an anchor tag with a @post.each do |post| 该视图只是带有@ post.each do | post |的锚标记。 loop.
环。
<a class="item" target="_blank" href="<%= post.short_url %">
<div>Short URL</div>
<%= post.short_url %>
</a>
Not sure if I'm calling the parameter at the routes or controller level incorrectly. 不知道我是否在路由或控制器级别错误地调用了该参数。
The find
method finds a record based on the id
(which is an integer). find
方法根据id
(整数)查找记录。 If you want to lookup a table based on any other field(in your case, short_url
), you need to use the find_by
method. 如果要基于任何其他字段(在您的情况下为
short_url
)查找表,则需要使用find_by
方法。
You're getting the error Couldn't find Post with 'id'=stack
as ActiveRecord
is looking up the posts
table for an id
of stack
which does not exist. 您收到错误消息,因为
ActiveRecord
正在posts
表中查找不存在的stack
id
,因此Couldn't find Post with 'id'=stack
的posts
。 Try 尝试
@post = Post.find_by(short_url: params[:short_url])
redirect_to @post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.