Reputation: 953
I have such code that should be available for each controller and all views.
@categs1= Category.where({:id => [2,7,15,16] })
@categs2= Category.where(:id => [18,21,24,31,32] )
@categs3= Category.where(:id => [34,35,36,40,42] )
But to make it available to all controllers I have to copy all over them. I tried to put in application controller, where it should be like default for all controllers, but it did't work.
I read suggestion about using helpers. How does it work ? Like partials in views ? I need to make one consisting this code and then just write require code where I need ??
Thanks :)
Upvotes: 0
Views: 99
Reputation: 24815
The concept itself is wrong. That is Wordpress way.
Such ids are data, not business logic. Your app should be separate from data.
The correct way is, suppose you have such three important categories 'foo', 'bar', 'barz' you want to treat specially in app, then set such things in table say adding a type
field.
Use a rake task or do it by yourself to assign these ids to 'foo', 'bar', 'barz'.
Then in controller
foo = Category.where(type: 'foo')
Upvotes: 3
Reputation: 1593
Create a filter in application_controller
called load_category
and load all the categories in a single query.
class ApplicationController < ActionController::Base
before_filter :load_category
private
def load_category
all_categories = Category.where({:id => [2,7,15,16,18,21,24,31,32,34,35,36,40,42] })
@categs1 = all_categories[0..3]
@categs2 = all_categories[4..8]
@categs3 = all_categories[9..13]
end
end
Upvotes: 3
Reputation: 2720
My proposal:
Category
named "type".@cars = Category.where(type: 'cars')
@bicycles = Category.where(type: 'bicycles')
@unicorns = Category.where(type: 'unicorns')
So no matter how many ID has, just need a filter by type and calls from views.
Upvotes: 1
Reputation: 877
You should be careful about loading collections only with their IDs ... Either way, Putting that code in the application controller seems to be the best solution. Try this in your application controller :
before_filter :set_categories
private
def set_categories
@categs1= Category.where({:id => [2,7,15,16] })
@categs2= Category.where(:id => [18,21,24,31,32] )
@categs3= Category.where(:id => [34,35,36,40,42] )
end
Upvotes: 2