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 に答える