2

I am trying to generate some count methods dynamically for a given array of model names that I can then use in a view/helper:

  # create dynamic count methods for each model we want                   
  ['model', 'other_model', 'next_model'].each do |name|
     class_eval{
       "def total_#{name.underscore}s_count
          total_#{name.underscore}s_count ||= #{name.camelcase}.all.count
        end"
      }
  end

However, I have a few questions:

  1. Where should this code go if I want to be able to call these methods in a view?
  2. What class would these methods be added to? For instance, how would I go about calling them since I'm not sure if they belong to the User, etc. class since they are for a bunch of models.
  3. Is there a better way of doing this?
2
  • What is the advantage of total_model_count over Model.count? Commented Jun 8, 2011 at 15:00
  • Keeping direct model calls out of my views Commented Jun 8, 2011 at 15:13

2 Answers 2

3

You should use a mixin and include it in the relevant model classes. http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/

The methods will be available on the model instances in your views.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem you're trying to solve (keeping your views from hitting model methods) isn't solved by delegating the same logic to a view helper. You should be doing this in your controllers if you want to stick to the MVC convention of keeping your views from triggering SQL queries.

def index
  models = Foo, Bar, Bat
  @counts = models.inject({}) do |result, model|
    result[model.name.downcase.to_sym] = model.count
    result
  end
end

You then have a nice hash of the counts of each of the models passed:

@counts #=> { :foo => 3, :bar => 59, :bat => 42 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.