Edgars
Edgars

Reputation: 953

How to keep Rails application DRY

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

Answers (4)

Billy Chan
Billy Chan

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

Ishank Gupta
Ishank Gupta

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

skozz
skozz

Reputation: 2720

My proposal:

  1. Set a new field in Category named "type".
  2. I'll would use like this:

@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

RedXVII
RedXVII

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

Related Questions