undefined method `comments_count' for Article

I am new to Rails. I followed the Getting Started Guide of Rails 5.1.4 to put up a blog. Everything is great.

However, in the next guide [Active Record Basics] in the Schema Conventions section we are introduced to a reserved column name called ‘(table_name)_count’. It says i can use ‘comments_count’ as a column name on the article model to get cached count of the comments associated with that article.

So i re-write my article index view like this:

<% @articles.each do |article| %> <%= article.comments_count %> <% end %>

When i reload the browser, i get the following error:

undefined method `comments_count’ for #Article:0x007fb51fb001b8 Did you mean? comments

What am i missing?

Hi Syed,

From Schema Conventions section:

There are also some optional column names that will add additional features to Active Record instances

It means that if you add columns (using migration) that have names following the naming conventions, you’ll get that feature.

The <relationship_name>_count convention is used for counter_cache option of belongs_to, which you can read about more here: http://guides.rubyonrails.org/association_basics.html#options-for-belongs-to