我有以下两种型号:
class Parent
has_many :children
class Child
belongs_to :parent
现在,我需要检查city
属性的值并获取Parent
。以上两个模型都有city
列。有时值是不同的,有时它们是相同的。我需要执行以下查询:
city_name = #some city name
parents = Parent.where(city: city_name).presence || Parent.joins(:children).where(children: {city: city_name})
如何将其组合为单个sql或activerecord查询?
答案 0 :(得分:2)
您可以使用or
:
Parent
.joins(:children)
.where(city: city_name)
.or(Parent.joins(:children).where(children: { city: name }))
无论您是否使用联接按其城市来获取“父母”,使用联接时,都需要“前缀”联接表以过滤其行。
如果您对此不满意,可以使用字符串版本
Parent
.joins(:children)
.where('parents.city = :city OR children.city = :city', city: city_name)