Rails View Helper Methods in controller


Do you want to use view helper_method in your controller to achieve some desired output. Rails provides a lot of view helpers, for example link_to, mail_to, pluralize, etc. One way to archive this in Rails 3 is to call view_context inside the controller to create a new ActionView instance for a controller, then all helper methods will be available through this instance in the controller.

# app/controllers/posts_controller.rb
class PostsController < ActionController::Base
  def show
    # ...
    tags = view_context.generate_tags(@post)
    email_link = view_context.mail_to(@user.email)
    # ...
  end 
end
# app/helpers/posts_helper.rb
module PostsHelper
  def generate_tags(post)
    "Generate Tags"
  end
end

No comments

Powered by Blogger.