2013-07-14 59 views
1

到目前爲止,我已經實現了一個具有身份驗證(用戶控制器和會話控制器)的簡單用戶,並且我想使用用戶#編輯路由和更新來訪問MyAccount頁面當前用戶的電子郵件地址。問題是更新函數使用我想更改的電子郵件更新當前視圖,但不更新數據庫,因此,當我刷新時,@ user.email對象將返回到其初始值。謝謝!在Rails 4.0中編輯/更新當前會話中的用戶字段

class UsersController < ApplicationController 
    before_action :set_user, only: [:show, :edit, :update, :destroy] 
    def new 
    @user = User.new 
    end 

    def create 
    @user = User.new(user_params) 
    if @user.save 
    UserMailer.registration_confirmation(@user).deliver 
    redirect_to log_in_path, :notice => "Signed up!" 
    else 
    render "new" 
    end 
    end 

    def edit 
    @user = current_user 
    end 

    def update 
    respond_to do |format| 
     if @user.update(user_params) 
     format.html { redirect_to @user, notice: 'User was successfully updated.' } 
     else 
     format.html { render action: "edit" } 
    end 
    end 
end 

    private 
    def set_user 
     @user = current_user 
    end 

    def user_params 
     params.require(:user).permit(:email, :password, :password_confirmation) 
    end 
end 

我還添加了我創建的會話控制器。

class SessionsController < ApplicationController 
    def create 
    user = User.authenticate(params[:email], params[:password]) 
    if user 
    session[:user_id] = user.id 
    redirect_to root_url, :notice => "Logged in" 
    else 
    flash.now.alert = "Invalid email or password" 
    render "new" 
    end 
    end 

    def destroy 
    session[:user_id] = nil 
    redirect_to root_url, :notice => "Logged out" 
    end 
end 

我的路線如下:

get "log_in" => "sessions#new", :as => "log_in" 
    get "log_out" => "sessions#destroy", :as => "log_out" 
    get "sign_up" => "users#new", :as => "sign_up" 
    #get "my_account" => "users#show", :as => "my_account" 
    get "my_account" => "users#edit", :as => "my_account" 

    get "main/index" 

    resources :users 
    resources :sessions 

最後,我的應用程序控制器和aplication.html:

class ApplicationController < ActionController::Base 
    protect_from_forgery with: :exception 
    helper_method :current_user 

    private 

    def current_user 
    @current_user ||= User.find(session[:user_id]) if session[:user_id] 
    end 
end 

在application.html就是我曾經的CURRENT_USER方法:

<div id="user_nav"> 
<% if current_user %> 
    Logged in as <%= current_user.email %> 
    <%= link_to "Log out", log_out_path %> 
    <%= link_to "My Account", my_account_path %> 
<% else %> 
    <%= link_to "Sign up", sign_up_path %> 
    <%= link_to "Log in", log_in_path %> 
<% end %> 
</div> 
+0

在您的用戶控制器中,嘗試使用if @ user.update_attributes(user_params) –

+0

來替換@ user.update(:current_user),我也試過它,但對數據庫仍然沒有影響。 –

回答

3

我不是s URE爲什麼要使用

if @user.update(:current_user) 

它應該是這樣的:

if @user.update(user_params) 
+0

感謝您的回覆,我這樣做,因爲它更有意義,但錯誤仍然存​​在。 –

-2

我知道這很簡單,也許你已經糾正了這個,但是......

,而不是

if @user.update(user_paramas) 

嘗試

if @user.update(user_params) 
+0

Ups。我在這裏輸入了錯誤信息,但是在代碼中它沒有問題。我轉而使用Devise auth,它的功能就像一個魅力。無論如何 –

相關問題