0

首先,感谢大家花时间阅读这篇文章。非常非常感谢提前。

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

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

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

这是我的不同模型/关联的样子:

模型/提供者.rb

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

模型/课程.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

模型/位置.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 %>`

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

4

1 回答 1

2

您可以尝试Location.uniq.pluck(:name)将返回一组唯一位置名称。从提供者出发,您必须使用:joins(给定 a @provider

Location.joins(occurences: :course).where(courses: { provider_id: @provider.id }).uniq.pluck('locations.name')
于 2013-02-07T02:38:05.933 回答