rails activerecord查找具有属性的下一条记录

时间:2014-02-23 20:07:52

标签: ruby-on-rails activerecord

我是铁轨初学者,我有一个图像细节视图,其中只显示带有链接的图像。

如果链接网址具有属性show_image == false且下一个图像存在,则链接网址应重定向到下一个图像。

我该怎么做?

目前它看起来像这样:

  - if @picture.next.present? && (@picture.category.title == @picture.next.category.title)
    %a.picture-show{ :href => "#{@picture.next.id}" }
      = image_tag @picture.image.normal.url
  - else
    %a.picture-show{ :href => picture_path(params[:category_slug], @next.id) }
      = image_tag @picture.image.normal.url

1 个答案:

答案 0 :(得分:0)

唯一改变的是图像的网址,以便您可以使用帮助程序来解决问题

在你看来

%a.picture-show{ :href => next_image_url(@picture) }
  = image_tag @picture.image.normal.url

在你的助手

def next_image_url(picture)
  if picture.next.present?
    picture_path picture.next
  else
    picture_path picture
  end
end

如果你还没有计算出'next'的方法,那么它就是这样的

def next
  Picture.where('id > ?' self.id).order('id desc').where(show_image: true).first
end