Question

I have such two models:

class Article < ActiveRecord::Base
  belongs_to :articles_type
end




class ArticlesType < ActiveRecord::Base
  has_many :articles
end

and in controller i write:

@articles = Article.where(article_type_id: params[:id])

and in view(haml) i try:

= @articles.articles_type.id

= @articles.articles_types.id

= @articles.first.articles_type.id

= @articles.first.articles_types.id

how could i display this articles_type.id but for only first row?

now i get

undefined method `articles_type' 

but why? what i do wrong? how to display nested model id?

Was it helpful?

Solution 2

The undefined method message is because @articles does not have an articles_type method. You have to get to a single instance of an Article in order to use that method. You could do that with a call to @articles.first or by iterating on the collection.

= @articles.first.articles_type.id

is the line you want to use.

OTHER TIPS

@articles will be a collection of items, not just a single one (because you used the where method). You will have to do:

@articles.first.articles_type_id

(Also note that you don't have to do .articles_type.id, because the @articles.first already has the ID of the type)

Looks like you've got your logic backwards.

Based on your models, an article belongs to an article_type.

@articles.first.article_type.id
# OR @articles.first.article_type_id

Just looks like you're incorrectly pluralizing .article_types when it should be .article_type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top