有条件的link_to做阻止

时间:2014-10-02 13:31:33

标签: ruby-on-rails ruby ruby-on-rails-4

也许这比我想象的要简单,但是我在解决这个问题时遇到了问题。我有一个link_to块

<%= link_to(@animal.previous_animal, {class: 'prev-page'}) do
  <span class="glyphicon glyphicon-chevron-left"></span> Meet <span class="name"><%= @animal.previous_animal.name %></span>, the <%= animal_breed(@animal.previous_animal) %>
<% end %>

但我只想在previous_animal存在的情况下显示链接

def previous_animal
 animal = self.class.order('created_at desc').where('created_at < ?', self.created_at)
 animal.last if animal
end

通常在link_to中我可以做到

<%= link_to(@animal.previous_animal) if @animal.previous_animal %>

但是当我添加if子句时,我得到未定义的方法'name',所以它仍在运行&lt;%= @ animal.previous_animal.name%&gt;,即使我认为它在if语句中?

<%= link_to(@animal.previous_animal, {class: 'prev-page'}) if @animal.previous_animal do
  <span class="glyphicon glyphicon-chevron-left"></span> Meet <span class="name"><%= @animal.previous_animal.name %></span>, the <%= animal_breed(@animal.previous_animal) %>
<% end %>

2 个答案:

答案 0 :(得分:1)

<% if @animal.previous_animal %>
  <%= link_to(@animal.previous_animal, class: 'prev-page') do %>
    <span class="glyphicon glyphicon-chevron-left"></span> Meet <span class="name"><%= @animal.previous_animal.name %></span>, the <%= animal_breed(@animal.previous_animal) %>
  <% end %>
<% end %>

答案 1 :(得分:0)

你的link_to如果块令人困惑,它会导致你的问题,因为即使没有记录,你也会渲染内容。我会这样做:

#controller
@animal = Animal.find_by_id(params[:id])
@previous_animal = @animal && @animal.previous_animal
@next_animal = @animal && @animal.next_animal

#view
<% if @previous_animal %>
  <%= link_to(@previous_animal, {class: 'prev-page'}) do
    <span class="glyphicon glyphicon-chevron-left"></span> Meet <span class="name"><%= @previous_animal.name %></span>, the <%= animal_breed(@previous_animal) %>
  <% end %>
<% else %>
  <!-- anything you might want to render if there's no previous animal -->
<% end %>

此外,您的previous_animal方法可以稍微整理一下。

#model
def previous_animal
  Animal.order('created_at desc').where('created_at < ?', self.created_at).first
end

def previous_animal
  Animal.order('created_at').where('created_at > ?', self.created_at).first
end