2013-11-23 158 views
0

我希望在新用戶註冊時能夠將新用戶的IP地址發送到我的管理員帳戶。我有:通過電子郵件在紅寶石上發送IP地址

class UserMailer < ActionMailer::Base 
    default :from => '"Admin" <[email protected]>' 

    def registration_confirmation(user) 
    @user = user #needed in order to have access to user variables 
    def client_ip 
     @client_ip = request.remote_ip 
    end 
    mail(:to => "#{user.name} <#{user.email}>", :subject => "Welcome to MySite").deliver! 
    mail(:to => '"Admin" <[email protected]>', 
      :subject => "New Member", 
      :body => "New member #{user.name} with email #{user.email} and ip: #{@client_ip} has just signed up!", 
      :content_type => "text/html") 
    end 

end 

,我發現了錯誤:
NameError在UsersController#創建 未定義的局部變量或方法'要求」爲#

users_controller.rb

def create 
    @user = User.new(params[:user]) 
    if @user.save 
     UserMailer.registration_confirmation(@user).deliver 
     sign_in @user 
     redirect_to @user 
    else 
     render 'new' 
    end 
    end 
+1

請求方法在控制器中可用。如果你在郵件程序中需要它,你需要把它作爲一個arg來傳遞。 – thargor

+0

我通過添加參數進行更新(請參見上文)。我不再有任何錯誤,但在電子郵件中,IP地址是空白的。 – Jet59black

+1

你可以在你正在調用registration_confirmation的地方添加控制器代碼嗎?那就是你可以訪問有權訪問該IP的請求方法的地方。您可能應該將其作爲參數傳遞給registration_confirmation方法。 – thargor

回答

2

東西如:

def create 
    @user = User.new(params[:user]) 
    if @user.save 
     UserMailer.registration_confirmation(@user, request.remote_ip).deliver 
     sign_in @user 
     redirect_to @user 
    else 
     render 'new' 
    end 
end 


def registration_confirmation(user, client_ip = '0.0.0.0') 
    @user = user #needed in order to have access to user variables 
    mail(:to => "#{user.name} <#{user.email}>", :subject => "Welcome to MySite").deliver! 
    mail(:to => '"Admin" <[email protected]>', 
     :subject => "New Member", 
     :body => "New member #{user.name} with email #{user.email} and ip: #{client_ip} has just signed up!", 
     :content_type => "text/html") 
end 

您只能訪問控制器/視圖中的請求對象。所以你需要將值傳遞給郵件程序,如果這是你想要訪問它的地方。

+0

工作!只是currious,你是什麼原因添加'0.0.0.0'而不是僅僅client_ip?是因爲你無法傳遞一個空白值嗎? – Jet59black

+1

這是一個默認值,所以如果您需要手動發送電子郵件或其他東西,您可以調用:registration_confirmation(user),並將電子郵件設置爲0.0.0.0,這有時用於本地主機 – thargor

相關問題