ruby – ActiveRecord – 在连接模型中查找具有共享属性的所有对象

前端之家收集整理的这篇文章主要介绍了ruby – ActiveRecord – 在连接模型中查找具有共享属性的所有对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有三个型号
class Boat < ActiveRecord::Base
  belongs_to  :captain
  has_many    :boat_classifications
  has_many    :classifications,through: :boat_classifications
end

class Classification < ActiveRecord::Base
  has_many :boat_classifications
  has_many :boats,through: :boat_classifications
end

class BoatClassification < ActiveRecord::Base
  belongs_to :boat
  belongs_to :classification
end

我正在尝试编写一个简单的ActiveRecord查询来查找所有类型帆船的船只.类似于Boat.where(分类:“帆船”)

解决方法

我认为这可行:
Boat.joins(:classifications).where(classifications: { name: 'Sailboat' }) # name or whatever field contains Sailboat

生成查询

SELECT `boats`.* FROM `boats` INNER JOIN `boat_classifications` ON `boat_classifications`.`boat_id` = `boats`.`id` INNER JOIN `classifications` ON `classifications`.`id` = `boat_classifications`.`classification_id` WHERE `classification`.`name` = 'Sailboat'
原文链接:https://www.f2er.com/ruby/265089.html

猜你在找的Ruby相关文章