2016-08-12 62 views
0

合併友好URL後,我的edit_user路徑不會路由到users#edit操作。 edit_user_path助手呈現的URL是正確的。每當我點擊鏈接時,它都會首先嚐試轉到正確的URL,然後重定向root操作。Rails edit_user路徑不起作用

路線:edit_user_path GET /users/:id/edit(.:format) users#edit

鏈接ERB:<%= link_to 'Edit Account', edit_user_path(@user), class: 'button' %>

渲染HTML:http://localhost:3000/users/plopp/edit

控制器:

class UsersController < ApplicationController 

    before_action :require_signin, except: [:new, :create] 
    before_action :require_correct_user, only: [:edit, :update, :destroy] 

    def index 
    @users = User.all 
    end 

    def show 
    @user = User.find_by!(username: params[:id]) 
    @reviews = @user.reviews 
    @favorite_movies = @user.favorite_movies 
    end 

    def edit  
    end 

    def update 
    if @user.update(user_params) 
     redirect_to @user, notice: "Account successfully updated." 
    else 
     render :edit 
    end 
    end 
end 

    private 

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

    def require_correct_user 
    User.find_by!(username: params[:id]) 
    unless current_user?(@user) 
     redirect_to root_url 
    end 
    end 

回答

0

我想你在#require_correct_user

def require_correct_user 
    @user = User.find_by!(username: params[:id]) 
    unless current_user?(@user) 
     redirect_to root_url 
    end 
    end 
01有錯誤

你應該找到並分配用戶變量@user
處理#edit行動之前運行#require_correct_user方法,因爲

before_action :require_correct_user, only: [:edit, :update, :destroy] 

它檢查當前用戶通過#current_user?幫手傳遞@user變量,所以在這之前檢查你應該分配用戶該變量

+0

這樣做。每當我遇到這樣的錯誤時,我會花幾個小時嘗試過分追蹤,結果卻是如此明顯的疏忽。我希望隨着我獲得更多經驗而變得更好。 –