2

I have this which nicely gives me next and previous items:

scope :next, lambda {|id| where("id > ?",id).order("id ASC") } 
scope :previous, lambda {|id| where("id < ?",id).order("id DESC") }

def next
 Item.next(self.id).first
end

def previous
 Item.previous(self.id).first
end

In my view:

<%= link_to @item.previous, title: "xxx" do %>
<span class="glyphicon glyphicon-chevron-left" style="color:#eeeeee"></span>
<% end %>

I would like to enhance above so that I don't just get the next/previous item but the next/previous item which has the same :source_id (my item's have source_id).

Found two similar question here but can't apply it to my example:

How to have multiple conditions in a named scope?

Rails scope with 2 where clauses

TIA!

Community
  • 1
  • 1
Zsolt
  • 253
  • 3
  • 15

2 Answers2

1

Just add conditions to your scopes.

scope :next, lambda {|id, source_id| where("id > ? AND source_id> ?", id, source_id).order("id ASC") } 
def next
  Item.next(self.id, self.source_id).first
end

You have a lot of options if you want to keep around your old scope with just id--make a new scope with a different name, check if source_id is nil in your lambda block and give it a default value (or change the where clause).

I'd recommend not bothering with your scopes though, if you're only using them to define your next/previous methods. You could just cut to the chase with

def next
  Item.where("id > ?", self.id).first
end
Raynor Kuang
  • 483
  • 3
  • 11
  • thanks big time! Which one is better: with scope or without? Without is less code, more simple to me. Maybe it's faster too? – Zsolt Jun 16 '16 at 07:54
  • It's actually the exact same speed--if you look at the Rails guide on scopes, they're just syntatic sugar for class methods. I'd say without for form reasons, since it doesn't make sense to write a scope if you're never going to use the scope on its own. – Raynor Kuang Jun 16 '16 at 13:42
0

It's more universal to go for created_at comparison for the previous scope because id may be a random number (to hide the total number of purchases for example)

Kiryl Plyashkevich
  • 2,157
  • 19
  • 18