Rails edit_user路由无法正常工作

时间:2016-08-12 19:15:17

标签: ruby-on-rails routing

合并友好网址后,我的edit_user路径未路由到users#edit操作。 edit_user_path帮助器中呈现的URL是正确的。每当我点击链接时,它首先会尝试转到正确的网址,然后重定向root操作。

路线: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

1 个答案:

答案 0 :(得分: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

您应该找到并将用户分配给变量@user
由于

,在处理#edit操作之前运行#require_correct_user方法
 before_action :require_correct_user, only: [:edit, :update, :destroy]

它通过#current_user?帮助程序通过@user变量检查当前用户,因此在检查之前,您应该将用户分配给该变量