編集 3: このメソッドを介して作成したリンクにアクセスしようとすると、ユーザーの認証に使用されるデバイスを使用して、ユーザーとドキュメントのネストされたセットアップがあり、ActiveRecord::RecordNotFound エラーでコントローラーの get_document メソッドを指すエラーが発生します。
root :to => "users#index"
resources :users do
resources :documents
end
次に、すべてのドキュメントを次のようにリストしようとします。
@documents.each do |doc|
link_to(doc.title, [@user, doc])
しかし、コントローラーのプライベート get_user メソッドにアクセスしようとするとエラーが発生します。これを行う正しい方法は何ですか?
ドキュメントはユーザーに属していますが、それは user_id しか与えません。それを使用しますか?
private #get_user should not be called outside contoller
def get_user
@user = User.find(params[:user_id])
end
エラー: 外側のコントローラーに対してプライベート メソッドを呼び出してはなりません
編集: get_document メソッドが呼び出されているようです...
def get_document
@document = @user.documents.find(params[:id])
end
しかし、ドキュメント参照はルートに渡されていますね。
編集 2: ドキュメントのコントローラ コード:
class DocumentsController < ApplicationController
before_filter :get_user
before_filter :get_document, :only => [:show, :update, :edit, :destroy]
before_filter :authenticate_user!
load_and_authorize_resource
def new
@document = @user.documents.build
end
def index
if params[:tag]
@documnets = Document.tagged_with(params[:tag])
else
@documents = Document.all
end
end
def create
@document = @user.documents.build(params[:document])
if @document.save
flash[:notice] = "Document has been created."
redirect_to [@user, @document]
else
flash[:notice] = "Failed to create document."
render :action => "new"
end
end
def edit
end
def show
end
def update
if @document.update_attributes(params[:document])
flash[:notice] = "Update Complete"
redirect_to [@user, @document]
else
flash[:notice] = "Update Failed"
render :action => "edit"
end
end
def destroy
if @document.destroy
flash[:notice] = "document deleted."
redirect_to @user
else
flash[:notice] = "Can't delete document"
redirect_to [@user, @document]
end
end
private #get_user should not be called outside contoller
def get_user
@user = User.find(params[:user_id])
end
public
def get_document
@document = @user.documents.find(params[:id])
end
end