将named_scope与子模型计数一起使用
我有一个简单的父对象,有很多子对象。我正在尝试找出如何使用命名范围来仅带回具有特定数量孩子的父母。
这可能吗?
class Foo < ActiveRecord::Base
has_many :bars
named_scope :with_no_bars, ... # count of bars == 0
named_scope :with_one_bar, ... # count of bars == 1
named_scope :with_more_than_one_bar, ... # count of bars > 1
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
我希望做类似 Foo.with_one_bar
的事情,
我可以在父类上编写类似这样的方法,但我宁愿拥有命名范围的力量
I have a simple parent object having many children. I'm trying to figure out how to use a named scope for bringing back just parents with specific numbers of children.
Is this possible?
class Foo < ActiveRecord::Base
has_many :bars
named_scope :with_no_bars, ... # count of bars == 0
named_scope :with_one_bar, ... # count of bars == 1
named_scope :with_more_than_one_bar, ... # count of bars > 1
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
I'm hoping to do something like Foo.with_one_bar
I could write methods on the parent class for something like this, but I'd rather have the power of the named scope
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样调用:
Called like so:
我将为此使用 计数器缓存。因此,您需要进行以下迁移:
比您还需要像这样更改
Bar
模型:现在
bars
的计数缓存在foo
模型中,这将加快您对条形
计数的查询。。
这样,您每次发出此类请求时,就可以节省为每个
foo
计算bars
的时间我在观看关于计数器缓存的railscast时得到了这个想法: http://railscasts.com/episodes /23-counter-cache-column
* Active Record 中的新增功能 [Rails 4 2013 年倒计时]
I would use the counter cache for this. Therefore you need the following migration:
Than you need too change you
Bar
model like this:Now the count of
bars
is cached in thefoo
model, that will speed up your queries for the count ofbars
.Your named_scopes then have too look like this:
That way you can save time counting
bars
for eachfoo
every time you make such a request.I got this idea watching the railscast about counter cache: http://railscasts.com/episodes/23-counter-cache-column
* What's new in Active Record [Rails 4 Countdown to 2013]