undefined method `comments_count' for Article

33 views
Skip to first unread message

Syed Rakib Al Hasan

unread,
Dec 10, 2017, 1:28:42 AM12/10/17
to Ruby on Rails: Documentation
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| %>
    <tr>
      <td align="center"><%= article.comments_count %></td>
    </tr>
<% 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? 

Hendy Tanata

unread,
Dec 14, 2017, 2:01:08 AM12/14/17
to rubyonra...@googlegroups.com

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


-- 
Hendy

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Documentation" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-docs+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-docs@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-docs.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages