Felix
Felix

Reputation: 5619

Ruby on Rails self.joins or self.where doesn't work?

my actual code looks like this

user_lesson = self.where("worked = ? AND passed = ?", true, false).order("lessons.sort")

But it doesn't work ... error is:

undefined method `where' for #<Membership:0x000000059f22e8>

.. I've tried it this way:

user_lesson = Membership.joins("user_lessons").where("id = ? AND worked = ? AND passed = ?",self.id, true, false).order("lessons.sort")

But then I got this error:

Unknown table 'memberships': SELECT `memberships`.*
FROM `memberships` user_lessons
WHERE (id = 4 AND worked = 1 AND passed = 0)
ORDER BY lessons.sort

How should it look like correctly?

Original Query

user_lesson = self.user_lessons.find :first,
  :include => [:lesson],
  :conditions => ["worked = ? AND passed = ?", true, false],
  :order => "lessons.sort"

Upvotes: 2

Views: 1746

Answers (1)

neuronaut
neuronaut

Reputation: 2709

This is because the where method is defined at the class level rather than the instance level. In your second example (where you're doing Membership.joins) you are doing the right thing by calling joins and where on the Membership class rather than on an instance of that class. The reason you get an error with that second example is probably because you need to run your migrations to create the memberships table (if you have no migration you'll need to create one).

Upvotes: 5

Related Questions