Rails邮件程序存在会话持久性和发送电子邮件的问题

时间:2012-04-08 16:13:50

标签: ruby-on-rails rails-activerecord rails-routing

我正在研究Ryan Bates的Railscast#124:Beta邀请。我可以收到发送的电子邮件,但会话不会在通过电子邮件发送过程中持续存在。出于某种原因,当登录用户向朋友发送邀请时,该应用会注销该用户。这对我来说是一个谜。知道我做错了吗?

邀请控制器

class InvitationsController < ApplicationController

  def new
    @invitation = Invitation.new
  end

  def create
    @invitation = Invitation.new(params[:invitation])
    @invitation.sender = current_user
    if @invitation.save
      if current_user?(nil) 
         flash[:notice] = "Thank you, we will notify when we are ready."
         redirect_to root_path       
      else
        UserMailer.invitation(@invitation, signup_path(@invitation.token)).deliver
        flash[:notice] = "Thank you, invitation sent."
        redirect_to hunts_path 
      end
    else
      render :action => 'new'
    end
  end

end

模型/ invitation.rb

class Invitation < ActiveRecord::Base

  belongs_to :sender, :class_name => 'User'
  has_one :recipient, :class_name => 'User'

  validates_presence_of :recipient_email
  validate :recipient_is_not_registered
  validate :sender_has_invitations, :if => :sender

  before_create :generate_token
  before_create :decrement_sender_count, :if => :sender

  private

  def recipient_is_not_registered
    errors.add :recipient_email, 'is already registered' if User.find_by_email(recipient_email)
  end

  def sender_has_invitations
    unless sender.invitation_limit > 0
      errors.add_to_base 'You have reached your limit of invitations to send.'
    end
  end

  def generate_token
    self.token = Digest::SHA2.hexdigest([Time.now, rand].join)
  end

  def decrement_sender_count
    sender.decrement! :invitation_limit
  end

end

用户控制器

class UsersController < ApplicationController
  before_filter :authenticate, :only => [:index, :edit, :update, :destroy]
  before_filter :correct_user, :only => [:edit, :update]
  before_filter :admin_user,   :only => :destroy

  ...
  def new
   if current_user?(nil)# = nil #.signed_in?
      @user = User.new(:invitation_token => params[:invitation_token])
      @user.email = @user.invitation.recipient_email if @user.invitation     
      @title = "Sign up"

    else
      flash[:error] = "Why sign up again?  You're already in!"
      redirect_to(root_path) 
    end  
  end
  ...
end

的routes.rb

resources :users, :invitations
resources :sessions, :only => [:new, :create, :destroy]

match '/signup/',  :to => 'users#new'
match '/signup/:invitation_token', :to => 'users#new'
match '/signin',  :to => 'sessions#new'
match '/signout', :to => 'sessions#destroy'
match '/contact', :to => 'pages#contact'
match '/about',   :to => 'pages#about' 
match '/help',    :to => 'pages#help'

root :to => "pages#home"
match ':controller(/:action(/:id(.:format)))'

0 个答案:

没有答案