ruby-on-rails - ActiveRecord 通过 HABTM 引用查找记录

标签 ruby-on-rails activerecord

我有简单的书籍作者 HABTM 模型:

书籍 -> books_authors -> 作者

我有一个作者 ID + 标题字符串数组,需要查找是否已经有一本书具有该标题并且具有这些给定的作者。

有什么想法可以在 Rails 3 中使用 ActiveRecord 来做到这一点吗?

最佳答案

实现 habtm 的最佳实践现在是 has_many :though

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

关于ruby-on-rails - ActiveRecord 通过 HABTM 引用查找记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535261/

相关文章:

validation - 迁移表中存在 :true vs. null:false

ruby-on-rails - Rails 4 activerecord更新多个属性

ruby-on-rails - Rails ActiveRecord 序列化方法在测试环境中不起作用

ruby-on-rails - Rails : request. 子域在应用程序 Controller 中引发请求的 undef 方法

ruby-on-rails - CORS 与 Amazon S3 和 Cloudfront

sql - 如何在单个查询中从 ActiveRecord 中的父项中选择唯一子项?

mysql - 查找关联模型中日期范围内的差距 | Rails 上的 Ruby

ruby-on-rails - 使用轮胎从Elasticsearch中的查询中提高

sql - 在 Rails AR 中增加字段值的安全方法

ruby-on-rails - 有什么方法可以从 ActiveRecord 连接中找到服务器吗?