在Rails 4.0中编辑/更新当前会话中的用户字段

时间:2013-07-14 23:44:17

标签: ruby-on-rails ruby-on-rails-4

到目前为止,我已经实现了一个具有身份验证的简单用户(用户控制器和会话控制器),我想使用用户编辑路由和更新来访问MyAccount页面,比如当前用户的电子邮件地址。问题是更新功能正在用我想要更改的电子邮件更新当前视图,而不是数据库,因此当我点击刷新时,@ user.email对象将返回其初始值。谢谢!

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

最后,我的Application controller和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>

2 个答案:

答案 0 :(得分:3)

我不确定你为什么要使用

if @user.update(:current_user)

应该是这样的:

if @user.update(user_params)

答案 1 :(得分:-2)

我知道这很简单,也许你已经纠正了这个但是......

而不是

if @user.update(user_paramas)

尝试

if @user.update(user_params)