gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:08 26 4
gpt4 key购买 nike

我有三个模型

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(classifications: "Sailboat")

最佳答案

我认为这可行:

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'

关于ruby - ActiveRecord - 在连接模型中查找具有共享属性的所有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22484330/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com