0

大家好,

请原谅我在铁轨上的菜鸟。

所以这是我的问题。

所以我有一个类别模型和一个下面定义的行程模型

class Category < ActiveRecord::Base
  has_many :categorizations, :dependent => :destroy
  has_many :itineraries, :through => :categorizations
end

class Itinerary < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations
end

因此,在我看来,我正在遍历类别以分组显示行程。

<% @categories.each do |category| %>
<table>
  <thead>
    <tr>
      <th colspan="4"><%= category.name %></th>
    </tr>
  </thead>
  <tbody>
    <% category.itineraries.each do |itinerary| %>
      <tr>
        <td><%= itinerary.name %></td>
        <td><%= link_to 'Show', itinerary %></td>
        <td><%= link_to 'Edit', edit_itinerary_path(itinerary) %></td>
        <td><%= link_to 'Destroy', itinerary, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>
<% end %>

所以我想知道,我们如何显示尚未分类的行程?我四处搜索,发现在模型中使用范围将是可行的方法。

scope :without_categories, -> { includes(:categorizations).where( :categorizations => { :itinerary_id => nil } )}

我发现它不是很“干燥”,因为我必须编写另一个表来itinerary.without_categories再次迭代。

有没有一种方法可以让我们对它进行编码,从而categories.all显示其中包含uncategorized项目的所有内容?

谢谢你。

更新#1

决定在我的控制器中使用它,它在索引操作上构建一个新的“未分类”类别,并将添加到数组中。

def index
  uncategorized = Category.new
  uncategorized.name = "Uncategorized";
  uncategorized.itineraries = Itinerary.without_categories
  @categories = Category.all << uncategorized
end

我知道在 Rails 中,控制器应该尽可能瘦。但我想不出更好的方法。

谁有更好的答案,欢迎分享。谢谢!:)

4

1 回答 1

0

您只需在分类表中找到没有参考的行程。您可以为此进行嵌套查询。

SELECT * FROM itineraries where id NOT IN ( SELECT itinerary_id FROM categorizations')

只需在您的行程模型中执行一个方法,如下所示:

def self.uncategorized
  Itinerary.find_by_sql('SELECT * FROM itineraries where id NOT IN ( SELECT itinerary_id FROM categorizations)')
end
于 2013-09-24T12:06:19.557 回答