开发者

Combining custom joins with regular rails joins

开发者 https://www.devze.com 2023-02-23 04:13 出处:网络
I have models foo, bar, and baz like so # has a field join_condition_string class Foo < AR::Base :has_many :bar

I have models foo, bar, and baz like so

# has a field join_condition_string
class Foo < AR::Base
    :has_many :bar
end

# Has a field exclusion_critera
class Bar < AR::Base
    :belongs_to foo
end

# has a fields condition_string, exclusion_criteria
class Baz < AR::Base
end

I want to be able to Retrieve Foo's based on criteria from both Bar and Baz. As such i need to join to both models. I want to join to Bar using rails magic,

Foo.find(:all, :joins => :bar)

And I want to join Baz using a custom join.

Foo.find(:all, :joins=>"left join baz on baz.condition_string = foo.join_condition_string")

Independently these work great, but I can't seem to find a way to elegantly combine them.

I've tried 开发者_JAVA百科to do the naive thing and combine the two conditions in an array, to no avail.

Foo.find(:all, :joins=>["left join baz ...", :bar])

The docs claim that i can do Foo.find(:all, :joins => :bar, :joins => "left join baz ..."), but this doesn't seem like it should work (and it doesn't in rails 2.3.8), because the args to find are wrapped in a hash and the first :joins is lost.

Of course I could always combine the two into a single :joins string. However, how can these two calls be combined with as little raw sql as possible? Any ideas?

EDIT: The accepted answer does answer my question, but I still think there could be a better way.

EDIT 2: As rubyprince mentioned, this has been resolved in rails >= 3.0.0


This is probably a work around for your problem. You can keep these joins separately as 2 named scopes in the model and call them like this.

class Foo < AR::Base
  has_many :bars
  named_scope :joined_bars, :joins => :bars
  named_scope :joined_baz, :joins => "LEFT JOIN baz on ..."
end

Then you can call it in the controller like this

Foo.joined_bars.joined_baz

You can append any conditions or other parameters to the selected like this

Foo.joined_bars.joined_baz.all(:conditions => ..,
                               :limit => ..)

This will create a single SQL query with all joins, where, limit etc.

0

精彩评论

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

关注公众号