如何让上一个/下一个链接在 ROR 标头中工作 [英] How to get prev/next links working in a ROR header

查看:33
本文介绍了如何让上一个/下一个链接在 ROR 标头中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个艺术品数据库和每件艺术品的详细信息页面.当我将以下代码添加到我的 show.html.erb 页面时,链接效果很好.Next 带我到下一个艺术品,而 previous 带我回来.当没有前一个时,链接消失,反之亦然.

I have a database of artworks and detail pages for each artwork. When I add the following code to my show.html.erb page the links work great. Next takes me to the next artwork, and previous takes me back. When there is no previous, the link disappears and vice versa.

show.html.erb 包括

show.html.erb includes

<% if @artwork.next.present?  %>
  <%= link_to "Next &rarr;".html_safe, @artwork.next %>
<% end %>
<% if @artwork.previous.present? %>
  <%= link_to "&larr; Previous".html_safe, @artwork.previous %>
<% end %>

但我真的很想将这些链接放入我的标题中,它在我的应用程序页面中呈现为部分内容.但是,我注意到,当我将链接复制/粘贴到部分中时,我得到一个NoMethodError in Artworks#index undefined method `previous' for nil:NilClass".我可以只使用 css 将页面上的链接向上移动,但这感觉很糟糕.从标题部分中获取这些链接的正确方法是什么?

But I really would like to put those links into my header, which is rendered as a partial within my application page. I've noticed, though, that when I copy/paste the links into the partial I get a "NoMethodError in Artworks#index undefined method `previous' for nil:NilClass". I could just use css to move the links up on the page, but that feels janky. What is the right way to get these links working from within the header partial?

模型(artwork.rb)有

Model (artwork.rb) has

  def previous
    Artwork.where(["id < ?", id]).order('rating DESC').last
  end

  def next
    Artwork.where(["id > ?", id]).first
  end

控制器(选定部分)

def index
    if params[:tag] 
      @artworks = Artwork.tagged_with(params[:tag])
    elsif params[:series]
      @artworks = Artwork.tagged_with(params[:series])
    else
      @artworks = Artwork.all
    end
  end

def show
    @artwork = Artwork.friendly.find(params[:id])
end

application.html.erb 有

application.html.erb has

<%= render 'layouts/header' %>

推荐答案

除了检查 nextprevious 是否存在之外,还要检查以确保 @artwork 存在:

Instead of checking to see if next and previous are present also check to make sure @artwork is present:

<% if @artwork.present?  %>
  <% if @artwork.next.present?  %>                                                                                                                                                                                                                       
    <%= link_to "Next &rarr;".html_safe, @artwork.next %>
  <% end %>
  <% if @artwork.previous.present? %>
    <%= link_to "&larr; Previous".html_safe, @artwork.previous %>
  <% end %>
<% end %>

这篇关于如何让上一个/下一个链接在 ROR 标头中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆