0

I'm a rails beginner and I have an image detail view where just the image is displayed with a link.

The link url should redirect to the next image if it has the attribute show_image == false and if next image exists.

How can I do it?

at the moment it looks like this:

  - 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 Answers1

0

The only thing that is changing is the url of the image so you can use a helper to figure it out

in you view

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

in your helper

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

if you have not calculate the method 'next' yet then it would be something like this

def next
  Picture.where('id > ?' self.id).order('id desc').where(show_image: true).first
end
sonnyhe2002
  • 2,091
  • 3
  • 19
  • 31
  • nearly done, I just wanted now to check if the next picture has attrbute "show_image" == false. Can I do it like this: Picture.where('id > ?' self.id).where('show_image' false).order('id desc').first – user3344204 Feb 23 '14 at 20:30
  • I want to know where does it redirect to, the picture show page? If you have a show_image attr in your model, then you can also put that logic in the next method. – sonnyhe2002 Feb 23 '14 at 20:34
  • I had a the following in my picture.rb: scope :next, lambda {|id| where("id > ?",id).where(show_image: false).order("id ASC") } def next Picture.next(self.id).first end – user3344204 Feb 23 '14 at 22:00
  • Minor correction to your `next` method. As written it will return the first last record created (i.e. the record with the greatest `id`). It should be rewritten as follows: `Picture.where('id > ?' self.id).order('id asc').where(show_image: true).first` – Yechiel K Apr 17 '18 at 00:26