简体   繁体   English

如何仅显示在 rails 3 中有关联的结果?

[英]How can i show only the results that have an association in rails 3?

I am trying do a where statement that only brings up results that have that particular association.我正在尝试做一个 where 语句,它只显示具有该特定关联的结果。

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.我试图让我的结果只返回具有状态(金、银和/或青铜)的公司,而不是那些没有状态的公司。

If you have an associative table called companies_statuses:如果您有一个名为 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)")

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 .假设公司has_many:statuses ,那应该给你正确的查询。

From the Ruby on Rails guide on Active Record Associations:来自 Ruby on Rails 指南关于 Active Record 关联:

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

To know whether there's and associated object just check association.nil?:要知道是否存在和关联的 object 只需检查 association.nil?:

if @supplier.account.nil?如果@supplier.account.nil?

@msg = "No account found for this supplier" @msg = "未找到此供应商的帐户"

end结尾

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

Company.joins(:statuses).select("DISTINCT(companies.id), companies.*, statuses.*")

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

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