【发布时间】:2014-12-20 03:05:48
【问题描述】:
如果我有这种关系:
Foo has_many :bars
Bar belongs_to :foo
我想在 Foo 模型中指定一个范围,因为我想在其中过滤一些字段(即 where("code='AV1' OR code='AH5'")
bars 中有 Foo 的外键。如何指定适合上述过滤器的bars?像Bar.foo.customScope 这样的东西,假设我也想过滤Bar 中的东西?
Bar.where(".....").foo.customScope?
编辑
是的,code 是 foo 表中的一个字段
bars 表中有几百个条目。它们每个都有一个指向foos 表(模型Foo)的外键。我想从foos 表中获取具有特定code 的所有bars 的列表。例如
foos:
id, code
1,okay
2,not okay
3,somewhat okay
bars:
id,foo_id,otherstuff
1,1,blah
2,1,blob
3,2,hello
4,3,hurray
如果我的 Foo 模型如下所示:
class Foo < ActiveRecord::Base
has_many :bars
def self.goodCodes
where("code='okay' or code='somewhat okay')
end
end
我的 Bar 模型如下所示:
class Bar < ActiveRcord::Base
belongs_to :foo
end
我想调用一些东西来获取所有符合条件的 Bar 项目以及满足 goodCodes 条件的 foos 项目。我认为它会是这样的:Bar.where(....).foo.goodCodes 或者,
Bar.where(...).each do |row|
if row.foo.goodCodes
##do something
end
end
【问题讨论】:
-
那么,您是否尝试过简单地在 Foo 类中创建范围?那没用?
标签: ruby-on-rails activerecord