Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/405.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 活动记录哈希,希望在每个循环期间“注入”更多数据_Ruby On Rails - Fatal编程技术网

Ruby on rails 活动记录哈希,希望在每个循环期间“注入”更多数据

Ruby on rails 活动记录哈希,希望在每个循环期间“注入”更多数据,ruby-on-rails,Ruby On Rails,我有一个类别表和一个帖子表。帖子属于一个类别。我想输出所有类别的列表,以及该类别中最新的帖子 我觉得有点傻,但我已经做了几个小时了。我曾尝试在查询类别时加入并包含,但我遇到的问题仅限于每个类别的最新帖子 然后我尝试创建自己的散列或数组,但我一直遇到问题。所以,在我浪费更多时间之前,我想下面是我能想象的下一个最干净的工作方式 我真的很感激在如何实现这一点上能得到的任何帮助 以下是我的代码剥离到最低限度 db/schema.rb app/models/category.rb 以下是假设性的。 提升@

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

我觉得有点傻,但我已经做了几个小时了。我曾尝试在查询类别时加入并包含,但我遇到的问题仅限于每个类别的最新帖子

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

我真的很感激在如何实现这一点上能得到的任何帮助

以下是我的代码剥离到最低限度

db/schema.rb

app/models/category.rb

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


首先创建一对一关联:

class Category
  has_one :latest_post, :order => "created_at DESC", class_name => "Post"
end
然后快速加载:

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

而且。。。瞧

首先创建一对一关联:

class Category
  has_one :latest_post, :order => "created_at DESC", class_name => "Post"
end
然后快速加载:

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

而且。。。瞧

我想你希望:order=>created_在desc得到最新的,否则这个顺序是升序,你会得到第一篇文章。我想你希望:order=>created_在desc得到最新的,否则这个顺序是升序,你会得到第一篇文章。
<% @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 %>
---
- !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
...
---
- !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
...
class Category
  has_one :latest_post, :order => "created_at DESC", class_name => "Post"
end
@categories = Category.includes(:latest_post).all