i was wondering if it was possible to get the current object in a model? ie i have a
FavoriteRelationship model which
belongs_to :user
belongs_to :lesson
my lesson model is
has_many :favorite_relationships
has_many :users, :through => :favorite_relationships
i have an association with my user model as well (not important)
ive been trying to do the method inside my FavoriteRelationship
def lesson_owner
self.lesson.user
end
to retrieve the user that belongs to that lesson in the FavoriteRelationship but it doesn’t seem to work. it returns nothing, even when i do
self.lesson.inspect
retrieving even the lesson which is in the FavoriteRelationship model isn’t working. could someone shed some light on how to do this?
i essentially want the lesson that’s associated with the FavoriteRelationship model. in my FavoriteRelationship table, i have the attributes,
:id, :user_id, :lesson_id.
and the :lesson_id should be the value im trying to acquire so i can get the user afterwards
thank you for your help and time
@update.
so im basically using trying to grant a ‘badge’ when a user favorites someone elses lessons. i have..
def create
@lesson = Lesson.find(params[:favorite_relationship][:lesson_id])
puts 'before favorite'
current_user.favorite!(@lesson)
puts 'after favorite'
@favorite_relationship = @lesson.user
respond_to do |format|
format.html { redirect_to @lesson }
format.js
end
end
my badge granting comes from…
grant_on 'favorite_relationships#create', :badge => 'got-favorited',
:to => :lesson_owner
which takes in a method that returns who im granting to, that’s why i created that method.
when i do
puts self.lesson.inspect
nothing comes up, not nil or anything. i know that my favoriting works, it creates the relationship in the db. the only thing i could possibly think is happening is that…it tries to grant the badge before the relationship gets created. hmm…i put print statements and it does seem like it goes into lesson_owner after the create_favorite_relationship gets called and returns. maybe it hasn’t created it yet in the db? like a millisecond too fast? the favoriting happens asynchronously.
do i need to have some more associations set up?
So, what does this
self.lesson.inspectreturn?nilorNoMethodError?Show us your migrations and check what’s actually in the database.
This might be your relation is just missing the link to the lesson (
lesson_idis NULL)…