2011-07-15 8 views
2

だから私持ってこのようになりますオブザーバー:Mongoidコールバック関係は期待通りに動作しない

class RecipeObserver < Mongoid::Observer 

    def after_create(object) 
    puts object.user 
    puts "test" 
    end 

end 

そして私のように、細かい作業が、関係object.userがnilであることを持っているにもかかわらず、私のレシピクラスbelongs_toユーザーはhas_manyレシピもあります。私はここで間違って何をしていますか?


Updateはだからここ

私のコントローラのコードと私のモデルがあり、誰かが私を示してくださいできれば別のオブジェクトの作品を作成し、適切な観察者が、それは非常に参考になる方法:

class RecipesController < ApplicationController 
    respond_to :html 
    before_filter :authenticate_user!, :only => :new 

    # ... other actions 

    def new 
    @recipe = Recipe.new 
    respond_with @recipe 
    end 

    def create 
    @recipe = Recipe.new(params[:recipe]) 
    @recipe.save 

    respond_with @recipe, :notice => "You've created a recipe!" 
    end 
end 
(簡略化のために切り捨て)

マイモデル:

class Recipe 
    include Mongoid::Document 

    # ... other methods and such 

    belongs_to :user 
end 

class User 
    include Mongoid::Document 

    field :name 

    # ... other methods and such 

    has_many :recipes 
end 

大きな問題はafter_createメソッドのobject.userを呼び出すことはnilですが、例外をスローすることもなく、何も返されないことです。最も奇妙なことがわかります。開始方法はわかりませんこれをデバッグする。

+0

レシピを作成してユーザーを割り当てる方法を貼り付けることはできますか? また、レシピモデルがattr_accessible/protected stuffでないことを確認してください。 – kain

+0

ちょっと@kain、あなたの入力のおかげで、私はあなたにもう一度感謝して時間がある場合は、あなたが覗いて私の他の論理nのいくつかを追加しました。 –

答えて

1

実際にユーザーをどこにでもレシピに割り当てるようには見えません。お試しください:

def create 
    @recipe = current_user.recipes.build(params[:recipe]) 
    @recipe.save 

    respond_with @recipe, :notice => "You've created a recipe!" 
end 
関連する問題