【问题标题】:rails - Build queries, the combining them?rails - 构建查询,将它们组合起来?
【发布时间】:2011-06-12 18:46:37
【问题描述】:

基于我的应用,我需要根据一组条件抓取用户。

@usersSet1 = XXX based on a bunch of conditions

@usersSet2 = XXX based on a bunch of different conditions

@usersSet3 = XXX based on a bunch of even more different conditions

然后我想把这 3 条结合起来,取前 100 条记录。对使用 Rails 完成此操作有任何想法吗?谢谢

【问题讨论】:

  • 你想如何组合它们?追加,排序,什么?

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

您应该在模型中定义范围:

# model
scope :set1, where(some_conditions), ...
scope :set2, where(some_conditions), ...
scope :set3, where(some_conditions), ...
scope :top_100, limit(100)

给这些范围适当的名称。当然,您需要通过某种方式 order 它。 然后你可以调用:

@usersSet1 = User.set1
@usersSet2 = User.set2
@usersSet3 = User.set3

@usersset123 = User.set1.set2.set3.top_100

它将AND set1、set2 和 set3 中的所有条件。

【讨论】:

  • 好吧,事实证明这不起作用,因为每个范围都像这样添加到 SQL 中,SET 1 = XXX,AND 2 = x,AND 3,我需要的是 OR 不是和。想法?
  • 没有简单的方法来链接作用域和OR 它们。您必须编写使用 OR 的新范围并调用它。它不是干的,但它有效。你也可以看看这里:stackoverflow.com/questions/3684311/… 和这里:stackoverflow.com/questions/3016983/…
【解决方案2】:

最好的方法是执行一个 SQL 查询来拉回具有这些条件的字段。例如:

@users = User.all(select => "city,state,last_name,first_name,…", :limit => 100)

现在您拥有所有列。所以你继续:

@usersSet1 = @users.select{|a| a.state == 'Charlotte' && a.state == 'NC') #pulls back users in Charlotte
@usersSet2 = @users.select{|b| b.last_name == 'Smith' } #pulls back users that have the last name of Smith.
@usersSet3 = @users.select{|b| b.first_name == ('John' || 'Joe') } #pulls back users that have the first name of John or Joe.

等等……在我看来,这更具可扩展性。

【讨论】:

  • 谢谢,但这里的问题是每个查询都需要另一个表用于逻辑。比如权限等
猜你喜欢
  • 1970-01-01
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多