views:

150

answers:

2

I am still newer to Rails... I need to write a self.method on my Product model to find the next Product per position. I am showing 1 Product on a page, and want the next one in the list.

def self.next_product
product = Product. # current product.position +1
end

obviously this won't work... I am still new to writing methods. anyone?

I am using Rbates Railscast 147 and Acts_as_list, I need to figure out how to get the next product

thanks so much

A: 

acts_as_list already adds methods for getting the next and previous items, they are called higher_item (position - 1) and lower_item (position + 1). However, they are instance methods, not class methods (self.) because to find "the next item" in a list, you need to start with an item (an instance of the Product class), not the Product class itself.

=> p = Product.first
<Product id: 1, position: 1>
=> p.lower_item
<Product id: 2, position: 2>
Jeff Dallien
Thanks so much for that info. So I would write a simple instance variable in the controller, @product = Product.find(:first :conditions {position first})then in the view just pull that instance variable, then setup a link_to with that instance method? I appreciate the help
TJ Sherrill
A: 
class Product
 def next_product
   lower_item or self
 end
 def previous_product
   higher_item or self
 end
end

link_to "Next", product_path(@product.next_item) 

link_to "Previous", product_path(@product.previous_item)