2012-10-09 54 views
3

我還在學習Rails,我有一個簡單的項目,用戶通過提供他們的電子郵件和密碼進行註冊。我希望用戶在點擊電子郵件鏈接之前處於非活動狀態。我跟着RailCasts'例如重置密碼,這是我想出了:在Rails中通過電子郵件激活用戶

我添加了兩個新的領域,以我的用戶模型:

  • activation_token:字符串
  • 活躍:布爾

裏面User.rb我有以下兩種方法:

def send_activation 
    generate_token(:activation_token) 
    UserMailer.activation(self).deliver 
end 

def generate_token(column) 
    begin 
    self[column] = SecureRandom.urlsafe_base64 
    end while User.exists?(column => self[column]) 
end 

我創建了一個新的控制器稱爲ActivationsController,並在其內部都有一個方法:

def update 
    @user = User.find_by_activation_token(params[:id]) 

    @user.update_attribute(:active, true) 
    flash[:success] = "Your account is now activated." 
    redirect_to root_path 
    end 

裏面routes.rb我加了這條路線:

resources :activations, only: [:update] 

我用下面的方法創建一個UserMailer

def activation(user) 
    @user = user 
    mail to: user.email, subject: "Account Activation" 
end 

rake routes說了以下內容:

activation PUT /activations/:id(.:format) activations#update 

裏面activation.text.erb我有這樣的:

To activate your account, please click the link below: 
<%= link_to activation_url(@user.activation_token), method: :put %> 

現在,當我嘗試註冊用戶我得到這個錯誤之前,該郵件被髮送出去:

No route matches {:method=>:put} 

什麼想法?

邁克

回答

2

你缺少鏈接文本:

<%= link_to 'TEXT', activation_url(@user.activation_token), method: :put %> 
+0

現在我得到這個錯誤: 沒有路線匹配[GET]「/ activations/icrvr5uNahnA5fpVjVTDEw」 – mikeglaz

+0

您必須在您的路線中使其成爲獲取請求。只有在你的瀏覽器與一些軌道工程ujs magick – phoet

+0

隨着PUT,我得到這個URL /activations/:id(.:format),它有一個地方爲我可以通過params [:id]得到的id。但有了GET,我得到/activations(.:format)。有一種方法可以通過GET請求將一個:id加入到URL中嗎?或者有另一種方法可以訪問activation_token? – mikeglaz

0

我知道這是很老,但我也有這個問題。我想回答它來幫助其他人。

我相信問題是使用激活#更新操作,您應該使用激活#編輯操作,因爲該操作使用GET請求而不是PATCH請求。由於用戶在電子郵件中收到此消息(因此它位於Rails服務器之外),因此它應該是普通的舊GET鏈接。

此外,至少在RAILs 4(這個問題可能是以前的方式)中,你可以在初始變量之後用散列值將params添加到你的url路徑中。所以......

<%= link_to "TEXT", edit_account_activation_url(@user.activation_token, email: @user.email)

(那是,如果你想驗證用戶的電子郵件activation_token。)

我不知道你的代碼的其餘部分是如何設置的,但至於到您對第一個答案的最後評論,這裏有一些來自railstutorial.org/book的文章,我發現它們很有幫助。

Because we’re modeling activations using an Account Activations resource, the token itself can appear as the argument of the named route

此外,這本書指出(在腳註)爲什麼我們要使用的編輯操作,而不是更新的...

It might even make more sense to use an update action, but the activation link needs to be sent in an email and hence should involve a regular browser click, which issues a GET request instead of the PATCH request required by the update action.

來源:Rails Tutorial: Chapter 10