如何在Rails 3.2中的(多个)关联中返回唯一记录

时间:2013-02-07 01:57:10

标签: ruby-on-rails rails-activerecord

首先,感谢每个人花时间阅读这篇文章。很多,非常感谢提前。

我正在尝试弄清楚如何检索提供商可能拥有的所有 唯一 位置名称。

我的第一个想法是在Provider模型中编写一个方法,该方法将迭代所有课程然后发生并返回一个唯一位置列表。

我已经查看了Rails api中的.uniq方法,但没有任何运气。

以下是我的不同模特/协会的样子:

模型/ provider.rb

class Provider < ActiveRecord::Base
  has_many :courses
  has_many :teachers
end

模型/ course.rb

class Course < ActiveRecord::Base
  has_many :occurrences, :dependent => :destroy
  belongs_to :provider
end

模型/ occurrence.rb

class Occurrence < ActiveRecord::Base
  belongs_to :course
  belongs_to :location
end

模型/ location.rb

class Location < ActiveRecord::Base
  attr_accessible :name
  has_many :occurrences
end 

实现这一目标的最佳方式是什么?

在阅读完成后我试过这个:

我在Provider模型中创建了一个unique_locations方法,它有以下代码(基于你的答案)

def unique_locations
  Location.joins(occurrences: :course).where(courses: { provider_id: self.id }).uniq.pluck('locations.name')
end`

并在我看来使用它:

<% @provider.unique_locations.each do |l| %>
  <%= l %><br>
<% end %>`

但我仍然得到非独特的结果。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试Location.uniq.pluck(:name),它将返回一系列唯一的位置名称。从提供商处开始,您必须使用:joins(给定@provider

Location.joins(occurences: :course).where(courses: { provider_id: @provider.id }).uniq.pluck('locations.name')
相关问题