我有三个型号
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'