views:

85

answers:

2

Having a bit of difficulty figuring out how to create a named_scope from this SQL query:

select * from foo where id NOT IN (select foo_id from bar) AND foo.category = ? ORDER BY RAND() LIMIT 1;

Category should be variable to change.

What's the most efficient way the named_scope can be written for the problem above?

+6  A: 
  named_scope :scope_name, lambda { |category|
    { 
      :conditions => ["id NOT IN (select foo_id from bar) AND foo.category = ?", category],
      :order => 'RAND()',
      :limit => 1
    }
  }
zed_0xff
+3  A: 

More of a comment than an answer but it won't really fit...

zed_oxff is on the ball.

To simplify things and keep them DRY, you might consider defining discrete named scopes instead of one big one, and chaining them together.

For example:

named_scope :random_order, :order => 'RAND()'
named_scope :limit, :lambda => { |limit| :limit => limit }
named_scope :whatever, ...

So you would use them as follows:

Person.random_order.limit(3).whatever
nfm