如何使用 Squeel 指定此查询?
假设我有一个模型:
class Question < ActiveRecord::Base
attr_accessible :title # it has title attribute
has_many :pictures
end
我想定义一个名为 completed
的 scope
查询,它:
返回符合以下条件的所有问题:
- 标题不为空 或
- 至少有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,您可以使用 Squeel 来做到这一点!只需这样写下您的范围即可:
希望我有所帮助。
Of course you can do this with Squeel! Just write your scope this way:
Hope I helped.