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

时间:2011-08-14 19:56:20

标签: ruby-on-rails ruby-on-rails-3 where nested-includes

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

例如:

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

4 个答案:

答案 0 :(得分:0)

您的用例表达不是很明确,但我认为您想要的是找到状态与指定地址匹配的公司:

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

假设公司has_many :statuses,那应该给你正确的查询。

答案 1 :(得分:0)

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

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

要知道是否有关联对象只是检查   association.nil:

     

if @ supplier.account.nil?

     

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

     

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

答案 2 :(得分:0)

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

答案 3 :(得分:0)

如果您有一个名为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)")