开发者

How can I find a rails object based on the properties of their has_many :through relations?

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.


Foo.find(:all, :conditions=>["bonks.name = ?", 'awesome'], :include => :bonks)

should generate something along the lines of

Select * from foos, bars, bonks where bars.foo_id = foo.id and bonks.bar_id = bar.id and bonks.name = 'awesome'


In 1.2 - an SQL fragment in a :joins argument is your best choice here. There's no better way to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜