2012-03-02 5 views

答えて

2

HABTMを実装するためのベストプラクティスは、今にhas_manyです:

models/Book.rb 
class Book < < ActiveRecord::Base 
has_many :authors 
has_many :authorships, :through => author 

models/Authorship.rb 
class Authorship < ActiveRecord::Base 
belongs_to :book 
belongs_to :author 

models/Author.rb 
class Author < ActiveRecord::Base 
has_many :authorships 
has_many :authors, :through => :authorships 
+0

HABTMを作るのに問題はありませんが、そのタイトルといくつかの著者IDで書籍を見つけることはできますか? – aristofun

0

かかわらず、このような何かが(未テストを!)動作するはずです:

books. 
    joins('inner join books_authors on books.id = book_id'). 
    where(:title => 'search_title'). 
    where('author_id in (?)', author_ids.join(',')). 
    group('id'). 
    having('count(*) = ?', author_ids.size) 

アイデアは著者があなたをフィルタリングすることです検索している書籍の著者数と検索している著者数を比較します。

+0

私はあなたのことを理解しようとしている間、別の解決策に来ました:) – aristofun

0

私がこれまでに見つかった最良の解決策はこれです:

Book.find(:all, :joins => :authors, 
       :conditions => 
          ["books.title = ? AND authors_books.author_id IN (?)", 
          book_title, 
          [1,2,3]) 

しかし残念ながら、あなたは今より少なく著者(1、または1 + 2など)

で本を削除するために、その後反復処理する必要があり、私SQL INステートメントを何らかの "_is_exactly_this_collection_"操作に置き換える方法を見つけ出す必要があります。

関連する問題