Sharethefun
Sharethefun

Reputation: 824

Ruby on Rails Collect Returns enclosed array (variable:undefined method `model_name' for Array:Class)

I had a controller that was returning all the articles of my website

 @articles = Article.find(all)

and a partial that used to render the @articles array.

I have changed my controller to :

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

So I can return some other data as well

After inspection on the Rails Console I found out that the problem is that the output array of collect does not match the Article.find(all)

Output array of find(all)

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

Output array of collect

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

When I'm trying to render the parcial i get:

variable:undefined method `model_name' for Array:Class 

My Index

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

and then the parcial:

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

Does anyone knows how to overcome the problem with the double brackets [[ ]] of the array?

Upvotes: 0

Views: 963

Answers (1)

PeterWong
PeterWong

Reputation: 16011

First, for the first line, I think you have a typo that should be :all instead of all :D

t.articles returns you a collection of articles.

So map {|t| t.articles} gives you a collection of collections of articles (the array of arrays).

You could try this:

@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.

Upvotes: 1

Related Questions