Rails设计两个编辑路由,一个用密码,另一个没有密码

时间:2015-11-19 06:35:02

标签: ruby-on-rails devise

我想允许用户拥有两个编辑页面,一个是需要密码的默认Devise页面,另一个是编辑页面,允许他们在没有密码的情况下编辑其个人资料的某些部分。

我看过像this这样的指南页面,允许他们在不提供密码的情况下编辑自己的个人资料。但是,我希望用户可以使用这两个选项,而不只是一个。

我将如何做到这一点?

我的尝试

我试图在用户控制器中创建我自己的更新路由,这将解决问题但是当用户重置密码时会产生问题,因为它被路由到用户#更新,这将导致错误,因为没有在Devise中重置密码期间可用的用户。

class UsersController < ApplicationController
  before_action :authenticate_user!, :only => [:crop] #:edit , :update

  def show
    @user = User.find(params[:id])
    authorize @user

  end

  def update
      @user = User.find(params[:id])
      authorize @user
      if @user.update(user_params)
        flash[:success] = "You have successfully updated your profile!"
        redirect_to user_path(@user)
      else
        render :edit
      end
  end
  def crop
    @user = User.find(params[:id])
    authorize @user
  end
  def index

  end

    private
    def user_params
       params.require(:user).permit(:poster_image_crop_x, :poster_image_crop_y, :poster_image_crop_w, :poster_image_crop_h)
    end

end

路线

Rails.application.routes.draw do

  resources :users,only: [:show] do
    member do
      get :crop
    end
 end
  devise_for :users, :controllers => { :omniauth_callbacks => "callbacks",:registrations => :registrations,:passwords => "passwords" }
  as :user do
    get "/login" => "devise/sessions#new"
    get "/register" => "devise/registrations#new"
    get "/edit" => "devise/registrations#edit"
    delete "/logout" => "devise/sessions#destroy"
  end

1 个答案:

答案 0 :(得分:1)

Devise的代码建议创建自己的控制器。如果来自UsersController中的操作,它们可能总是需要传递密码。所以你应该创建一个单独的控制器,我们称之为ProfilesController,这个控制器就像你的普通控制器,虽然它没有更新Profile模型,但直接用户模型......实际上没什么特别的,只需检查授权并让用户更新任何您希望直接在用户模式下使用该字段,不要忘记授权您希望用户更新的字段:

class ProfilesController < ApplicationController

 def index
 end
 ....... more code

  def update
      @user = User.find(params[:id])
      authorize @user
      if @user.update(user_params)
        flash[:success] = "You have successfully updated your profile!"
        redirect_to user_path(@user)
      else
        render :edit
      end
  end

  ....... more code

    private
    def user_params
       params.require(:user).permit(:poster_image_crop_x, :poster_image_crop_y, :poster_image_crop_w, :poster_image_crop_h)
    end
end

并将resources :profiles添加到路线文件中。