简体   繁体   English

在两个模型上匹配has_many关联

[英]Matching has_many association on two models

I have a job which has_many categories I have a business which has_many categories. 我的工作有has_many类别,我的业务有has_many类别。

Currently I'm only assigning 1 category to both job and a business but this will change later which is why I've created the has_many association. 目前,我只为工作和业务分配1个类别,但是稍后会更改,这就是为什么我创建has_many关联的原因。

The categories assigned to businesses and jobs are from the same category table selected with a select menu with the intention of matching them. 分配给企业和职位的类别来自同一类别表,该类别表是通过选择菜单选择的,目的是使它们匹配。

If have a job, how can I find businesses that match the jobs category. 如果有工作,我如何找到与工作类别匹配的企业。

For example job = Job.find(1) 例如job = Job.find(1)

> job.categories.first.name
 => "programmer"

If I want to find all Businesses listed that have the programmer category how can I do this? 如果我要查找列出的所有具有programmer类别的企业,该怎么办?

I think I might need a join or include similar to this but I'm not sure how this should be written exactly. 我想我可能需要一个联接或包含与此类似的联接,但是我不确定应如何准确地编写联接。

Business.includes(:categories).where(:categories == ...)

Your code is almost right. 您的代码几乎是正确的。 This should work: 这应该工作:

Business.joins(:categories).where(categories: {name: 'programmer'})

Or if you have multiple categories: 或者,如果您有多个类别:

Business.joins(:categories).where(categories: {name: ['programmer', 'other']})

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

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