2012-03-02 60 views
2

我有簡單的書,作者HABTM模型:的ActiveRecord通過HABTM發現記錄引用

書籍 - > books_authors - >作者

我有作者的ID +標題字符串數組,需要找到,如果有已經是一本有這個頭銜的書,並且完全是作者的作品。

任何想法都可以在Rails 3中使用ActiveRecord嗎?

回答

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 2012-03-02 15:14:30

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

我試着瞭解你的時候已經到了另一個解決方案(見下文):) thansk很多 – aristofun 2012-03-04 19:57:13

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_」操作...任何想法?