Rails 2.3: How to turn this SQL statement into a named_scope

左心房为你撑大大i 提交于 2019-12-23 19:12:32

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2937537/rails-2-3-how-to-turn-this-sql-statement-into-a-named-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!