如何使用 Squeel 指定此查询?

发布于 2024-11-24 08:21:37 字数 855 浏览 8 评论 0原文

假设我有一个模型:

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

Suppose I have a model:

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

I want to define a scope query called completed that:

Returns all questions whose:

  • title is not empty
    OR
  • has at least 1 picture

How can I do that?

So far, I have:

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

It'd be nice if I could just say:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鼻尖触碰 2024-12-01 08:21:51

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

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

希望我有所帮助。

Of course you can do this with Squeel! Just write your scope this way:

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

Hope I helped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文