Need a self. method on a Rails model using Acts_as_list
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 开发者_StackOverflowwork... 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
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>
- See the acts_as_list documentation for descriptions of the methods it adds to your class.
- See this blog post for a description of class and instance methods in Ruby.
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)
精彩评论