Add support for rendering views to a rails api only application

2.1k views Asked by At

I built an api only rails app, but since i'm using a 3rd party email service, I need to be able to render the email template into a string to pass it to the mailing service wrapper gem. So far any attempt to render templates into a string returns an empty string, and i suspect it is because the application is configured to be API only. Ho do I add support to rendering templates into a string?

If this is not the case, please let me know. I'm using postmark mail service. postmark-rails gem, which integrates into standard rails mailers didn't work at all, and plain postmark gem (which uses postmark API instead of postmark SMTP server) works fine, but now my problem is producing the proper html for the email.

this is what I'm trying:

html = render_to_string(
            partial: "transfer_mailer/transfer.html.erb",
            locals: {
                :@body => @body,
                :@campaign => @campaign,
                :@chat => @chat
                }
        )

but it returns empty string.

My setup involves Rails 5.0.1, ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux], Sidekiq 4.2.7, and in production im using nginx/1.10.2 and Phusion Passenger 5.1.1. Production environment is deployed in an azure virtual machine, and I added both inbound and outbound rules for allowing traffic through ports 25, 465, 2525, and 587.

Any help would be really appreciated.

2

There are 2 answers

1
max pleaner On

Looking at the docs for render_to_string, it looks like the path doesn't need to include .html.erb, so maybe removing that will fix it.

You can see here for some example code:

In your case, it would be:

   render_to_string(
       partial: '/transfer_mailer/transfer',
        locals: {
            :@body => @body,
            :@campaign => @campaign,
            :@chat => @chat
        },
       layout: false
    )

Also make sure the partial filename starts with an underscore, even though you don't include it with render_to_string or render calls.

0
Peter Pan On

There is the other way to use render_to_string for resolving your issue. Please see the code below.

@body = XXX
@campaign = YYY
@chat = ZZZ
html = render_to_string(
  file: 'transfer_mailer/transfer.html.erb'
)

Hope it helps.