ruby – ActiveRecord – 在连接模型中查找具有共享属性的所有对
发布时间:2020-12-16 23:10:16 所属栏目:百科 来源:网络整理
导读:我有三个型号 class Boat ActiveRecord::Base belongs_to :captain has_many :boat_classifications has_many :classifications,through: :boat_classificationsendclass Classification ActiveRecord::Base has_many :boat_classifications has_many :boats
我有三个型号
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' (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |