2

我有一个类别表和一个帖子表。帖子属于一个类别。我想输出所有类别的列表以及该类别中的最新帖子。

我觉得有点傻,但我已经为此工作了几个小时。我在查询类别时尝试过joininclude但我遇到了仅限于每个类别的最新帖子的问题。

然后我尝试创建自己的哈希或数组,但我一直遇到问题。所以在我浪费时间之前,我认为以下将是我能想象到的下一个最干净的工作方式。

对于如何实现这一目标,我将不胜感激。

以下是我的代码(精简到最低限度)。

数据库/schema.rb

ActiveRecord::Schema.define(:version => yyyymmddhhmmss) do

  create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at",    :null => false
    t.datetime "updated_at",    :null => false
  end

  create_table "posts", :force => true do |t|
    t.string   "title"
    t.integer  "category_id"
    t.datetime "created_at",   :null => false
    t.datetime "updated_at",   :null => false
  end

end

应用程序/模型/category.rb

class Category < ActiveRecord::Base
  ...
  has_many :posts
  ...
end

应用程序/模型/post.rb

class Post < ActiveRecord::Base
  ...
  belongs_to :category
  ...
end

应用程序/控制器/categories_controller.rb

class CategoriesController < ApplicationController
  ...
  def index
    @categories = Category.all
    # The following loop is what my question is about
    @categories.each do |c|
      latest_post = Post.where(:category_id => c.id).order('published_at DESC').first
      # "Inject" post.id and post.title in to the current @categories hash
    end
  end
  ...
end

应用程序/视图/类别/index.html.erb

<% @categories.each do |c| %>
  ...
  <h4><a href="<%= category_path(c) %>"><%= c.name %></a></h4>
  # The following line is how I envision the output to work
  <p><a href="<%= post_path(c.post_id) %>"><%= c.post_title %></a></p>
  ...
<% end %>

raise @categories.to_yaml

---
- !ruby/object:Category
  attributes:
    id: 1
    name: General
    created_at: 2013-01-10 22:08:57.291758000 Z
    updated_at: 2013-01-10 22:09:02.414022000 Z
...

以下是假设性的。 raise @categories.to_yaml

---
- !ruby/object:Category
  attributes:
    id: 1
    name: General
    created_at: 2013-01-10 22:08:57.291758000 Z
    updated_at: 2013-01-10 22:09:02.414022000 Z
    post_id: 80
    post_title: Lorem Ipsum
...
4

1 回答 1

4

首先创建一个一对一的关联:

class Category
  has_one :latest_post, :order => "created_at DESC", class_name => "Post"
end

然后急切加载:

@categories = Category.includes(:latest_post).all

还有……瞧!

于 2013-01-11T17:20:26.337 回答