我有简单的书籍作者HABTM模型:
书籍 - > books_authors - >作者
我有一个作者ID +标题字符串数组,需要查找是否已经有一本书具有该标题并且确切地拥有那些作者。
在Rails 3中使用ActiveRecord做任何想法吗?
答案 0 :(得分: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
答案 1 :(得分: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)
我们的想法是按照您要搜索的作者进行过滤,然后将每本书中找到的作者数量与您要搜索的作者数量进行比较。
答案 2 :(得分:0)
我到目前为止找到的最佳解决方案是:
Book.find(:all, :joins => :authors,
:conditions =>
["books.title = ? AND authors_books.author_id IN (?)",
book_title,
[1,2,3])
但不幸的是,你必须迭代才能删除作者较少的书籍(1或1 + 2等)
现在我需要找出一种用某种“_is_exactly_this_collection_”操作替换SQL IN
语句的方法......有什么想法吗?