Reputation: 9617
Right now in my view I have this:
@categories.each do |category|
And I need to define @categories in each method in controller duplicating the code.
def home
@categories = Category.where(:parent_id => '').order("id").each
end
def contacts
@categories = Category.where(:parent_id => '').order("id").each
end
How do I get rid of repetition?
Upvotes: 0
Views: 993
Reputation: 13477
There is no need to define class or global variables since results might be changed between queries. I suppose add some memoization and extract duplicate into separate method:
def home
categories
end
def contacts
categories
end
def categories
@categories ||= Category.where(:parent_id => '').order("id").each
end
And better to define scope
in model:
class Category < ActiveRecord::Base
scope :categories_without_parent, -> { where(:parent_id => '') }
end
In controller method categories
will look like:
def categories
@categories ||= Category.categories_without_parent
end
Upvotes: 1