如何根据 has_many :through 关系的属性找到 Rails 对象?
模型:Foo、Bar、Bonk
class Foo < ActiveRecord::Base
has_many :bars
has_many :bonks, :through => :bars
end
class Bar < ActiveRecord::Base
has_many :bonks
end
我如何检索与名称为“awesome”的 Bonk 关联的 Foo 对象列表
我知道如何使用 Foo.find(... ) 涉及一个 :join 和一个 :condition。不过,我想做的是避免将那么多原始 sql 塞入其中(特别是当中间有多个模型时)。
显然,类似的东西
Foo.find(:all, :conditions=>["bonks.name = ?", 'awesome'])
不会像它生成的那样工作。
Select * from foos where bonks.name = 'awesome'
遗憾的是,我在这里处理的是 Rails 1.2 应用程序,但我不认为此功能从那时起就发生了变化。
Models: Foo, Bar, Bonk
class Foo < ActiveRecord::Base
has_many :bars
has_many :bonks, :through => :bars
end
class Bar < ActiveRecord::Base
has_many :bonks
end
How can I retrieve a list of Foo objects that are associated with a Bonk whose name is "awesome"
I know how to do with with a Foo.find(...) that involves a :join and a :condition. What I want to do though is avoid shoving that much raw sql into there (especially when there's more than one model in the middle).
Something like
Foo.find(:all, :conditions=>["bonks.name = ?", 'awesome'])
which, obviously, doesn't work as it'd generate
Select * from foos where bonks.name = 'awesome'
Sadly, I'm dealing with a rails 1.2 app here but I don't think this functionality has changed since then.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该生成类似的东西
should generate something along the lines of
在 1.2 中 -
:joins
参数中的 SQL 片段是您的最佳选择。没有更好的方法可以做到这一点。In 1.2 - an SQL fragment in a
:joins
argument is your best choice here. There's no better way to do this.