Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing URL Helpers when Rendering Partials from Rails Models

I have to render some templates and send the HTML block to SendGrid for email substitution. So, unfortunately, I am doing some rendering in model like this:

    view = ActionView::Base.new(Rails.configuration.paths["app/views"].first)
    view.render(:partial => template_name)

Even if I added:

    view.extend Rails.application.routes.url_helpers
    view.extend ActionView::Helpers::UrlHelper
    view.extend ApplicationHelper

The partial don't have access to URL Helpers like url_for unless I explicit define the module like in the following:

    Rails.application.routes.url_helpers.edit_user_url(user, :host => Rails.application.config.action_mailer.default_url_options[:host])

Is there a cleaner way to use URL Helper in templates called from models?

like image 811
Gary L Avatar asked Dec 07 '13 05:12

Gary L


2 Answers

In Rails 5, it is simple:

ApplicationController.render partial: 'my/partial'

It will have all your helpers loaded

more info: https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions

like image 70
Dinatih Avatar answered Oct 12 '22 05:10

Dinatih


A workaround I found is to pass the url_helpers as part of the locals:

url = Rails.application.routes.url_helpers
view = ActionView::Base.new(Rails.configuration.paths['app/views'].first)
view.render(partial: template, locals: locals.merge(url: url))

and then in the view:

<%= url.thing_path %>

Also note you must to configure your default_url_options with:

# config/environments/production.rb
  config.after_initialize do
    Rails.application.routes.default_url_options = { host: 'production.server.com' }
  end

# config/environments/development.rb
  config.after_initialize do
    Rails.application.routes.default_url_options = { host: 'localhost', port: 3000 }
  end
like image 23
Alter Lagos Avatar answered Oct 12 '22 06:10

Alter Lagos