Andy Harvey
Andy Harvey

Reputation: 12653

Adding variables to routes/ url paths in Rails3 mailer

I've been searching for an answer to what should be a simple question. Can anyone point me in the right direction, or at least tell me what I should be searching for?

I'm implementing a Rails3 beta invite system a la Ryan Bates - http://railscasts.com/episodes/124-beta-invitations

The mailer generates a relative link. How to I preprend the host path? (I already have config.action_mailer.default_url_options set up in development.rb)

-- The relevant bits of my routes file.

devise_for :users,  :path_prefix => 'registration', :controllers => {:registrations => 'users/registrations'} do
    get   "registration/users/sign_up/:invitation_token" => "users/registrations#new"
  end

I've made some minor adjustments to reflect updates in Rails and to play nicely with Devise. The controller now looks like this

class InvitationsController < ApplicationController
  def new
    @invitation = Invitation.new
    @title = "Invite a friend"
  end

  def create
    @invitation = Invitation.new(params[:invitation])
    @invitation.sender = current_user
    if @invitation.save
        if user_signed_in?
            Mailer.invitation(@invitation, new_user_registration_path(@invitation.token)).deliver
            redirect_to root_url, :notice => "Thank you, your friend will receive their invitation soon."
        else
            redirect_to root_url, :notice => "Thank you, we'll let you know when the next batch of invites are availale."
        end
    else
        if current_user.invitation_limit > 0
            render :action => 'new', :alert => "Sorry, there was a problem! Please try a again."
        else
            redirect_to root_url, :alert => "Sorry, you don't have any invitations left. Please wait until we issue more."
        end

    end
  end
end

And the mailer like this:

class Mailer < ActionMailer::Base

  def invitation(invitation, sign_up)

    subject     'Invitation'
    recipients  invitation.recipient_email
    @greeting = "Hi"
    @invitation = invitation
    @signup_url = sign_up
    @sender = invitation.sender_id
    invitation.update_attribute(:send_at, Time.now)       
  end
end

I appreciate any pointers that would help be better understand why this is happening.

Thanks!

Upvotes: 0

Views: 1939

Answers (1)

Austin Taylor
Austin Taylor

Reputation: 5477

The first problem is that you need new_user_registration_url instead of new_user_registration_path. Url = absolute, path = relative.

You may need to show us your routes for help with the second problem. It looks like your parameter is being treated as a format. Perhaps you need a custom mapping? Something like:

match '/users/sign_up/:token' => 'users#sign_up', :as => :new_user_registration

Since you've set up default_url_options, I would expect you to be able to call the url helper in the mailer view, rather than passing it in from the controller.

Upvotes: 1

Related Questions