Active Record Hash,想在.each循环期间“注入”更多数据

时间:2013-01-11 17:11:42

标签: ruby-on-rails

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

我觉得有点傻,但我现在已经在这几个小时了。我在查询类别时尝试了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
...

1 个答案:

答案 0 :(得分:4)

首先创建一对一关联:

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

然后急切加载:

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

而且......Voilà!