我想在我的自定义not_found(404)模板中获得更多动态错误消息。最常见的问题是人们正在寻找不再在我们的数据库中的艺术家或曲目。如果找不到艺术家或曲目,请呈现特定的消息。
我收到此错误:
Error during failsafe response: Couldn't find Track without an ID
我希望它在数据库中找不到曲目或艺术家但不会破坏应用程序。 任何想法?问题出在我的 custom_404_message方法中。
def custom_404_message
artist = Artist.find_by_slug(params[:slug])
track = Track.find(params[:id])
if params.has_key? "artists" && artist.nil?
@message = "It looks like the artist you are looking for is not on our site."
elsif params.has_key? "tracks" && track.nil?
@message = "It looks like the song you are looking for is not on our site."
else
@message = "The page you are looking for does not exist :-("
end
@message
end
def not_found
@message = custom_404_message
render file: "#{Rails.root}/app/views/errors/not_found.html.erb", layout: false, status: 404
end
<div id="content">
<section id="mm-not-found">
<header id="mm-not-found-landing">
<div class="cover-image header-bg" style="background-image: url(//marmoset-music-standard.s3.amazonaws.com/assets/headers/forest-5d7e462b4e278fb7b241a57e654dca5a.jpg); background-size: cover; background-position: 50% 50%; background-repeat: no-repeat no-repeat;"></div>
<hgroup>
<div class="contain">
<div class="error-icon"><span></span></div>
<h1>Ooops! Sorry for the confusion.</h1>
</div>
</hgroup>
</header>
<article>
<div class="contain">
<h2><%= @message %></h2>
<em>If you feel like this is a problem on our end, please <a href="/contact" data-bypass="true">contact us</a>.</em>
</div>
</article>
</section>
</div>
</div>
</body>
</html>
修改
最终有效:
def custom_404_message
artist = Artist.find_by_slug(params[:slug])
track = Track.find_by_id(params[:id])
if params[:slug] && artist.nil?
@message = "It looks like the artist you are looking for is not on our site."
elsif params[:id] && track.nil?
@message = "It looks like the song you are looking for is not on our site."
else
@message = "The page you are looking for does not exist :-("
end
@message
end
答案 0 :(得分:1)
为了在寻找音轨时不引发错误:
track = Track.find_by(id: params[:id])
现在,如果找不到曲目,track
将nil
而不是引发错误。