Let's say I have the following model:
# video.rb
class Video < ActiveRecord::Base
has_many :collection_videos, :dependent => :destroy
has_many :collections, :through => :collection_videos
named_scope :in_collection_one,
:joins => :collection_videos,
:conditions => "collection_videos.collection_id = 1"
named_scope :in_foo_collections,
:joins => :collections,
:conditions => "collections.foo = true"
end
# collections.rb
class Collection < ActiveRecord::Base
has_many :videos, :through => :collection_videos
has_many :collection_videos, :dependent => :destroy
end
# collection_videos.rb
class CollectionVideos < ActiveRecord::Base
belongs_to :collection
belongs_to :video
end
If I make the following call:
Video.in_collection_one.in_foo_collections
I will get an error after ActiveRecord has constructed the SQL query complaining about doing multiple joins - it will attempt to join on :collection_videos twice (wrong, should only join once), and :collections once (this is correct). This is likely caused by a b开发者_开发技巧ug in rails but I'm wondering if there is a way around it.
Note: I am using Rails/ActiveRecord version 2.3.2
Could you use :include
instead of :join
? See this question for an example of someone using :include
to do joins.
精彩评论