【问题标题】:Rails 3: has_many and whereRails 3:has_many 和 where
【发布时间】:2014-06-27 11:54:03
【问题描述】:

我有以下型号

class City < ActiveRecord::Base
  has_many      :dealers 
end

class Dealer < ActiveRecord::Base
  belongs_to    :city
end

我需要找到所有有经销商的城市。如何编写where() 以获得所需的结果?

【问题讨论】:

  • dealers表的属性是什么?
  • 经销商将拥有city_id
  • 试试这个City.joins(:dealers).where("dealers.city_id =?",city.id)
  • 获取undefined local variable or method 'city'
  • 试试这个City.joins(:dealers).where("dealers.city_id =?",id)

标签: ruby-on-rails-3 activerecord rails-activerecord has-many


【解决方案1】:

仅查找有经销商的城市:

City.joins(:dealers)

如果一个城市没有经销商,则不会在结果中返回。

【讨论】:

  • 这并没有给我不同的城市,而是所有城市*所有经销商。我需要不同的城市。
【解决方案2】:

在尝试了一些选项之后,这就是我想出的。

City.joins(:dealers).group("dealers.city_id")

这将返回城市的完整记录。

找到更好的方法后编辑。

还有一个更好的方法来实现这一点,那就是在选择中使用uniq。所以新的查询将是

City.joins(:dealers).uniq

翻译成

SELECT DISTINCT `cities`.* FROM `cities` INNER JOIN `dealers` ON `dealers`.`city_id` = `cities`.`id`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多