Ruby on rails ActiveRecord通过HABTM引用查找记录
我有一本简单的书作者HABTM模型: 图书->图书\作者->作者 我有一个author id+title字符串数组,需要查找是否已经有一本具有该标题的书,并且恰好有那些给定的作者Ruby on rails ActiveRecord通过HABTM引用查找记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有一本简单的书作者HABTM模型: 图书->图书\作者->作者 我有一个author id+title字符串数组,需要查找是否已经有一本具有该标题的书,并且恰好有那些给定的作者 如何在Rails 3中使用ActiveRecord实现这一点?实现habtm的最佳实践现在有很多:尽管 models/Book.rb class Book < < ActiveRecord::Base has_many :authors has_many :authorships, :through =&
如何在Rails 3中使用ActiveRecord实现这一点?实现habtm的最佳实践现在有很多:尽管
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
models/Book.rb
教材<作者
models/Authorship.rb
类作者身份:作者身份
类似的方法应该可以工作(未经测试!):
我们的想法是按您正在搜索的作者进行筛选,然后将每本书找到的作者数与您正在搜索的作者数进行比较。到目前为止,我找到的最佳解决方案是:
Book.find(:all, :joins => :authors,
:conditions =>
["books.title = ? AND authors_books.author_id IN (?)",
book_title,
[1,2,3])
但不幸的是,您必须进行迭代才能删除作者较少的书籍(1或1+2等)
现在我需要找出一种方法,用某种“\u就是\u这个\u集合\u”操作来替换语句中的SQL
。。。有什么想法吗?制作HABTM没有问题,但我如何通过书名和一些给定的作者ID找到一本书呢?我找到了另一个解决方案(见下文),同时试图了解你的:)thansk很多
Book.find(:all, :joins => :authors,
:conditions =>
["books.title = ? AND authors_books.author_id IN (?)",
book_title,
[1,2,3])