So I have an observer which looks like this:
class RecipeObserver < Mongoid::Observer
def after_create(object)
puts object.user
puts "test"
end
end
And so I have that working fine, but the relationship object.user is nil, like even though my Recipe class belongs_to a user, which has_many recipes as well. What am I doing wrong here?
Update
So here is my controller code and my model, if someone could please show me how a proper observer that creates another object works, that would be very helpful:
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
My models (truncated for brevity):
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
So the big problem is that calling object.user in the after_create method is nil, but it doesn’t even throw an exception, just results in nothing being returned, which I find the most bizarre, I’m not sure really on how to start debugging this.
It doesn’t look like you’re actually assigning a user to the recipe anywhere. Try: