Martin Carlin

Rails Tips

in ruby, rails

Use helper functions in models and controllers

Sometimes you just need to use ActionView functions in your models or controllers.

A way to achieve this is to include them like so:

include ActionView::Helpers::TextHelper

but a nicer approach seems to be to use the function directly like so:

ActionController::Base.helpers.[FUNCTION_NAME] (arguments)

Better pagination - avoid multiple queries

First, do your query as normal but with one difference.

results ='SQL_CALC_FOUND_ROWS model.*')

and then immediately after, run the following:

total = ModelName.connection.execute('SELECT FOUND_ROWS()')

To get the actual total number, you can use .first on the total object.

This works even when using limit and offset in the original query.

comments powered by Disqus