发布于 2024-11-29 16:18:29 字数 148 浏览 0 评论 0原文

我正在尝试执行一个 where 语句,该语句仅显示具有特定关联的结果。

例如:

一个公司通过公司状态有多种状态。他们可以有多种状态,可以是金、银和/或青铜,或者根本没有。我试图让我的结果只返回具有状态(金、银和/或铜)的公司,而不返回没有状态的公司。

I am trying do a where statement that only brings up results that have that particular association.

For example:

A company has many statuses through company statuses. They can have multiple statuses that can be gold, silver, and/or bronze, or none at all. I am trying to have my results only return the companies that have a status (gold, silver, and/or bronze) and not the ones have no statuses.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

知你几分 2024-12-06 16:18:29

您的用例没有很好地阐明,但我认为您想要的是找到具有与指定状态匹配的状态的公司:

Company.includes(:statuses).where('status.name = ?', params[:status_name])

假设有一家公司,这应该会给您正确的查询has_many:状态

Your use case isn't very well articulated, but I think what you're wanting is to find Companies that have a status that matches a specified one:

Company.includes(:statuses).where('status.name = ?', params[:status_name])

That should give you the right query, assuming a Company has_many :statuses.

吾家有女初长成 2024-12-06 16:18:29

来自 Ruby on Rails 关于 Active Record Associations 的指南:

4.2.3 如何知道是否存在关联对象?

要知道是否存在关联对象,只需检查
Association.nil?:

如果@supplier.account.nil?

@msg =“找不到该供应商的帐户”

结束

http://guides.rubyonrails .org/association_basics.html#detailed-association-reference

From the Ruby on Rails guide on Active Record Associations:

4.2.3 How To Know Whether There’s an Associated Object?

To know whether there’s and associated object just check
association.nil?:

if @supplier.account.nil?

@msg = "No account found for this supplier"

end

http://guides.rubyonrails.org/association_basics.html#detailed-association-reference

时光匆匆的小流年 2024-12-06 16:18:29
Company.joins(:statuses).select("DISTINCT(companies.id), companies.*, statuses.*")
Company.joins(:statuses).select("DISTINCT(companies.id), companies.*, statuses.*")
夜未央樱花落 2024-12-06 16:18:29

如果您有一个名为 Companies_statuses 的关联表:

检索具有至少一种状态的所有公司

Company.where("EXISTS (select 1 from companies_statuses where companies_statuses.company_id = companies.id)")

检索没有状态的所有公司

Company.where("NOT EXISTS (select 1 from companies_statuses where companies_statuses.company_id = companies.id)")

If you have an associative table called companies_statuses:

to retrieve all companies with at least one status

Company.where("EXISTS (select 1 from companies_statuses where companies_statuses.company_id = companies.id)")

to retrieve all companies with no status

Company.where("NOT EXISTS (select 1 from companies_statuses where companies_statuses.company_id = companies.id)")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文