Skip to content

Instantly share code, notes, and snippets.

@bushymark
Created June 10, 2010 20:42
Show Gist options
  • Select an option

  • Save bushymark/433602 to your computer and use it in GitHub Desktop.

Select an option

Save bushymark/433602 to your computer and use it in GitHub Desktop.
##### I need to be able to eager load the notes element on the lesson element. Figured the best way to do it was through an
##### association.
##############
# doesn't work . . . conditions on associations don't take lambda's
class Note < ActiveRecord::Base
belongs_to :notable, :polymorphic => true
end
class Lesson < ActiveRecord::Base
has_one :note, :as => :notable, :conditions => lamda {['user_id = ?', User.current.id]}
end
##############
# Next step was to try default scope, doesn't work, no lambdas to default scope
class Note < ActiveRecord::Base
belongs_to :notable, :polymorphic => true
default_scope lambda {{:user_id => User.current.id}}
end
##############
# Okay, lets try this manually in my controllers and I will just create some magic model methods:
class Note < ActiveRecord::Base
belongs_to :notable, :polymorphic => true
end
class Lesson < ActiveRecord::Base
has_many :notes, :as => :notable
belongs_to :course
end
class Course < ActiveRecord::Base
has_many :lessons
end
#=> in my controller
course = Course.find params[:course_id]
lessons = course.lessons.find(:all, :include => [:other_stuff, :notes], :conditions => ["notes.user_id = ?", User.current.id])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment