我有一个多级模型结构,我正在尝试创建一个查询,我可以在其中搜索主父模型上的属性或关联更改中的最后一个模型。我的结构如下所示:
class Parent
attr_accessible :pname
has_one :child
end
class Child
has_many :infos
end
class Info
has_one :setting
end
class Setting
has_many :subsettings
end
class Subsetting
attr_accessible :sname
end
我正在尝试做的是创建一个 where 查询,我可以在其中提取所有父项,其中"pname = X"或"sname = X"。但是,我不确定如何创建如此深入的关联:有没有办法使用活动记录干净地做到这一点,还是直接创建 mysql 查询更好?
我正在徒手输入这个,所以这可能不是 100%,但你应该能够做如下的事情......
class Parent
has_one :child
has_many :infos, through: :child
has_many :settings, through: infos
has_many :subsettings, through: :settings
...
end
然后你应该能够打电话...
Parent.joins(:subsettings).where("parent.pname = ? OR subsetting.sname =?", x)
关于.where()
调用需要注意的两件事:
由于要针对多个联接表进行查询,因此需要在列前面加上表名。
表名是单数,而不是复数。这就是为什么
subsetting
而不是subsettings
.