0

我有一个控制器正在返回我网站的所有文章

 @articles = Article.find(all)

以及用于渲染 @articles 数组的部分。

我已将控制器更改为:

@articles = User.find(1).topics.map { |t| t.articles }

所以我也可以返回一些其他数据

在 Rails 控制台上检查后发现问题是 collect 的输出数组与 Article.find(all) 不匹配

find(all) 的输出数组

[#<Article id: 1, user_id: 2, title: "test">]

collect的输出数组

[[#<Article id: 1, user_id: 2, title: "test">]] 

当我试图渲染我得到的部分时:

variable:undefined method `model_name' for Array:Class 

我的索引

<%= render :partial => @articles%> 

然后是特别的:

<%= link_to_unless_current h(article.title), article %> <%= h(article.body) %>

有谁知道如何克服数组的双括号 [[ ]] 的问题?

4

1 回答 1

1

首先,对于第一行,我认为您应该有一个错字,:all而不是all:D

t.articles返回您的文章集合。

所以map {|t| t.articles}给你一个文章集合的集合(数组的数组)。

你可以试试这个:

@articles = User.find(1).topics.map { |t| t.articles }.flatten.uniq
# uniq if an article could belongs to two or more topics. Otherwise it is not needed.
于 2011-01-30T15:43:23.880 回答