Ruby on rails 按特定属性类型链接到上一条/下一条记录

Ruby on rails 按特定属性类型链接到上一条/下一条记录,ruby-on-rails,ruby,activerecord,ruby-on-rails-4,Ruby On Rails,Ruby,Activerecord,Ruby On Rails 4,我有一个目前由猫和狗组成的动物模型。我有一个名为animal_type的专栏,它将定义动物是什么 当我查看一个记录(显示动作)时,它可以是任何动物类型,我已经创建了下一个和上一个链接来循环浏览所有动物记录: def next_animal animal = self.class.order('created_at desc').where('created_at > ?', self.created_at) animal.first if animal end def previou

我有一个目前由猫和狗组成的动物模型。我有一个名为animal_type的专栏,它将定义动物是什么

当我查看一个记录(显示动作)时,它可以是任何动物类型,我已经创建了下一个和上一个链接来循环浏览所有动物记录:

def next_animal
 animal = self.class.order('created_at desc').where('created_at > ?', self.created_at)
 animal.first if animal
end

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

但仍不确定如何实施

def next_animal
 animal = self.class.order('created_at desc').where('created_at > ? and animal_type = ?', created_at, animal_type)
 animal.first if animal
end

只需将其添加到where中,如果使用作用域,则需要在上一个和下一个中使用if语句。

您可以执行以下操作:

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

# view
<% if previous_animal = @animal.previous_animal %> # local assignment in the if condition
  <%= 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 %>
<% end %>
#模型
动物
self.class.order('created_at desc')。where('created_at<?',self.created_at.)。where(animal_type:self.animal_type)。首先
结束
#看法
#if条件下的局部赋值
会见
  • previous\u animal
    方法被简化,在ActiveRecord::Relation上调用
    。first
    不能失败,但它可以返回
    nil
  • 我在if条件中使用了局部变量赋值,因为每次调用记录上的
    previous\u animal
    ,它都会触发一个SQL查询。这个局部变量有点像缓存(不会多次触发SQL查询)

你能把答案扩大一点吗?啊,别担心,我现在明白你的意思了,如果我要使用作用域,那么我必须使用if语句,将其添加到不再需要使用作用域的地方,谢谢Hanks Yoshiji,这两个答案在性能上有什么不同吗?是的,我刚刚用论点更新了我的答案。谢谢你,这是一个很好的解释。。。因此,我可以分配给局部变量越多,性能就越好?不,它不是那样工作的,你必须“知道”你的方法做了什么。在这里,该方法触发一个SQL查询来检索符合某些条件的记录。如果您调用它两次,它将触发SQL查询两次,这是不必要的,因为您在5毫秒之前就已经找到了它。在本例中,您可以“缓存”在局部变量中找到的记录,并直接使用它来使用该记录。如果您愿意,它的行为就像一条捷径,但它不是一条捷径。我不知道我是否清楚,也许不清楚。欢迎其他人在此提供意见!啊,这确实更有道理,不过我会多读一些关于这件事的书,谢谢
scope :dog_type, -> { where(animal_type: 'Dog') }
def next_animal
 animal = self.class.order('created_at desc').where('created_at > ? and animal_type = ?', created_at, animal_type)
 animal.first if animal
end
# model
def previous_animal
  self.class.order('created_at desc').where('created_at < ?', self.created_at).where(animal_type: self.animal_type).first
end

# view
<% if previous_animal = @animal.previous_animal %> # local assignment in the if condition
  <%= 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 %>
<% end %>