Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference self in a named scope? -- Rails 3.1 beginner

How do I reference self in the following?

scope :children, where("parent_id = ?", self.id)

self doesn't seem to work in this context

like image 755
Hopstream Avatar asked Nov 12 '11 14:11

Hopstream


1 Answers

Normally scopes are chained off the class, like this:

Foo.recent_entries.posts # Or whatever.

You'd need a lambda scope to get the same behavior:

scope :children_of, lambda { |o| where("parent_id=?", o.id }

I'm assuming you're trying to get a specific instance's children:

parent.children

This would be an instance method, but: this looks like a basic self-referencing association, too, rather than something needing a scope.

If you're making a tree there are gems for that, e.g., closure-tree, ancestry, and others.

like image 159
Dave Newton Avatar answered Nov 15 '22 05:11

Dave Newton