Ruby on rails 按特定属性类型链接到上一条/下一条记录
我有一个目前由猫和狗组成的动物模型。我有一个名为animal_type的专栏,它将定义动物是什么 当我查看一个记录(显示动作)时,它可以是任何动物类型,我已经创建了下一个和上一个链接来循环浏览所有动物记录: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
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条件下的局部赋值
会见
方法被简化,在ActiveRecord::Relation上调用previous\u animal
不能失败,但它可以返回。first
nil
- 我在if条件中使用了局部变量赋值,因为每次调用记录上的
,它都会触发一个SQL查询。这个局部变量有点像缓存(不会多次触发SQL查询)previous\u animal
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 %>