3

アカウントIDが提供されていないため、一致するルートがあります。/edit_account => accounts#editこれは、現在のユーザーIDを使用することになっており、account#editメソッドはと共有されてい/accounts/[:id]/editます。

class AccountController < ApplicationController
  ...
  def edit
    # This doesn't work:
    params = retrieve_id_if_missing(params)

    # This works:
    # aHash = params
    # params = retrieve_id_if_missing(aHash)
  end

  def retrieve_id_if_missing(params)
    # raise params.inpect => returns nil at this point
    if params[:id].nil? and !logged_in?
      redirect_to root_path
    else params[:id].nil?
      params[:id] = current_user.id
    end
      params
  end
end

私が抱えている問題はparams、クラスメソッドに渡されるとretrieve_id_if_missing、がになっていることnilです。ただし、params別の変数に割り当てると。たとえば、aHash渡す前にretrieve_id_if_missing、期待されるデータが含まれます{"action" => "edit", "controller" => "account"}

私は理由を探そうとしましたが、不足しています。誰かが私にこれが起こっている理由を説明できますか?

4

3 に答える 3

2

やってみました

class AccountController < ApplicationController
  ...
  def edit

    retrieve_id_if_missing


  end

  def retrieve_id_if_missing()
    if params[:id].nil? and !logged_in?
      redirect_to root_path
    else params[:id].nil?
      params[:id] = current_user.id
    end
      params
  end
end

params がメソッドのスコープ内にあることは間違いありません。

とにかく、これについてはgem deviseをチェックしてください。必要なものがすべて揃っている必要があります

デバイスを使用すると、そのまま使用できます

before_filer :authenticate_user!

コントローラーの上部

https://github.com/plataformatec/devise

于 2013-01-25T16:23:15.573 に答える
0

提供されたコードで params オブジェクトがオーバーライドされる理由についてはお答えできませんが、いくつかの考えがあります。

class AccountController < ApplicationController
  before_filter :retrieve_id_if_missing, only: :edit

  def edit
    # You'll find params[:id] prepopulated if it comes here,
    # else the request has been redirect
  end

protected

  # There should be no need to pass the params object around, it should be accessible everywhere
  def retrieve_id_if_missing
    if logged_in?
      params[:id] ||= current_user.id # conditional assignment will only happen if params[:id] is nil
    end

    # Redirect to root if params[:id] is still blank, 
    # i.e. user is not logged in and :id was not provided through route
    if params[:id].blank?
      flash[:alert] = 'You need to be logged in to access this resource.'
      return redirect_to root_url # early return!
    end
  end
end
于 2013-01-25T16:35:18.843 に答える