use view helper methods in controllers in rails 3

use view helper methods in controllers in rails 3

Sometimes it is comfortable to use view helpers in controller methods to customize things like pluralisation, links, mailto´s, etc . Rails provides a lot of view helpers, which can be used in controllers or normal helpers. In Rails 3 it is possible to call view_context inside a controller. This call will create a new ActionView instance for a controller, then all view helper methods will be available through this instance and you can simple do stuff like this:

def index
  if params[:search]
    @articles =[:search]).order("created_at DESC")
    count = view_context.pluralize(@articles.count, I18n.t("controllers.articles_controller.result"), I18n.t("controllers.articles_controller.results"))
    flash[:notice] = I18n.t("controllers.articles_controller.result_display", count: count, keyword: params[:search])
    @articles = Article.all
Matthias Frick
Ruby on Rails
0 Kommentare

Über den Autor

Matthias Frick
Matthias Frick, MSc.

Er ist ein langjähriger Ruby-on-Rails Entwickler und leitet das Unternehmen Frick-Web.

0 Kommentare zu "use view helper methods in controllers in rails 3"

Kommentar verfassen