1

到目前为止,我已经实现了一个带有身份验证的简单用户(用户控制器和会话控制器),我想使用 users#edit 路由进入 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

最后,我的应用程序控制器和 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>
4

2 回答 2

3

我不确定你为什么使用

if @user.update(:current_user)

它应该是这样的:

if @user.update(user_params)
于 2013-07-15T00:56:41.167 回答
-2

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

代替

if @user.update(user_paramas)

尝试

if @user.update(user_params)
于 2013-07-16T05:15:17.107 回答