【问题标题】:How to specify this query using Squeel?如何使用 Squeel 指定此查询?
【发布时间】:2011-07-15 16:32:33
【问题描述】:

假设我有一个模型:

class Question < ActiveRecord::Base   
   attr_accessible :title  # it has title attribute   
   has_many :pictures 
end

我想定义一个名为 completedscope 查询:

返回所有符合以下条件的问题:

  • 标题不为空 或
  • 至少有 1 张图片

我该怎么做?

到目前为止,我有:

class Question < ActiveRecord::Base   
   attr_accessible :title  # it has title attribute   
   has_many :pictures 

   scope :completed, where{title != ""}  # returns all questions with non-empty title
end

如果我能说:

class Question < ActiveRecord::Base   
   attr_accessible :title  # it has title attribute   
   has_many :pictures 

   scope :completed, where{title != "" || pictures.count > 0}
end

【问题讨论】:

    标签: ruby-on-rails-3.1 arel squeel


    【解决方案1】:

    当然,您可以使用 Squeel 做到这一点!只需这样写你的范围:

    scope :completed, joins{pictures.outer}.where{(title != "") | (pictures.id != nil)}.group{id}
    

    希望我能帮上忙。

    【讨论】:

    • 这个查询是否会返回所有要么有1)标题 2)至少1张图片的问题?或者这个查询是说“返回标题并且至少有一张图片的问题?”
    • 我正在寻找可以执行第一个查询的查询。也就是说,问题要么有标题,要么至少有一张图片。
    • 对不起,我误解了这个问题。你需要一个外部连接。我现在发布了正确的 squeel :)!
    • 非常感谢!顺便说一句,为什么要在最后调用 group ?
    • 这是因为问题有很多图片,并且最后的组可以确保问题行的不重复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-19
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多