简体   繁体   English

Rails Activerecord-链接关联以查询是否存在

[英]Rails Activerecord - chaining associations to query existence

Say I have the models Lists, People, Outfit. 假设我有模型列表,人员,服装。

Lists have many people, people have many lists and one outfit. 列表有很多人,人们有很多列表和一套衣服。 What is the most efficient way of checking if an outfit attribute 'name' exists in a given list with active-record? 检查带有活动记录的给定列表中服装属性“名称”是否存在的最有效方法是什么?

I would like this to return as a boolean if possible 如果可能的话,我希望以此为布尔值返回

As long as you have these associations on your models ( people in Outfit model and lists in Person model) and I got what you are asking this one should work for me 只要你有你的模型,这些协会( peopleOutfit模型,并listsPerson模型),我得到了你问这个人应该为我工作

Outfit.joins(people: :lists).exists?(lists: {id: your_list_id}, name: 'your_outfit_name')

and it's just one SQL query 这只是一个SQL查询

In alternative, you could just have 或者,您可能只有

Outfit.joins(:lists).exists?(lists: {id: your_list_id}, name: 'your_outfit_name')

and an association like 和类似的协会

has_many :lists, through: :people

This is the idea but I find hard try this kind of stuff 这是主意,但我发现很难尝试这种东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM