0

I have a Question model that has_many :answers & # answers_count :integer default(0)

On my Answer model, I have:

belongs_to :question, counter_cache: true

On my Question#Show page though, when showing my Answer#Form partial, I build an instance of an answer to be included in the form like so:

<%= render partial: "answers/form", locals: {answer: @question.answers.build(user: current_user)} %>

Right below that, I display the number of answers currently associated with this question. It should NOT include that unpersisted answer I just built in the form, yet it does.

This is the value of a @question:

[3] pry(#<#<Class:0x007fadab5f4d48>>)> question
=> #<Question:0x007fadab7f3478
 id: 51,
 title: "Chile loves Mexico A LOT",
 body: "5.times do\r\n puts \"*\"\r\nend\r\n\r\nputs \"Chile, Chile, Chile!\"\r\nputs \"Whips Mejico 7 - LOVE\"",
 user_id: 1546,
 created_at: Mon, 20 Jun 2016 09:05:09 UTC +00:00,
 updated_at: Mon, 20 Jun 2016 20:40:23 UTC +00:00,
 test_suite: "",
 expected_results: "",
 language: "ruby",
 comments_count: 1,
 runnable: false,
 answers_count: 0>

When I do various calls, I get different results:

[4] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers.count
  CACHE (0.0ms)  SELECT COUNT(*) FROM "answers" WHERE "answers"."question_id" = $1  [["question_id", 51]]
=> 0

That gives me the result I want, but it also does a DB-query which I am trying to avoid. The call to size seems to hit the cached value but it gives me the wrong value as you can see below.

[5] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers.size
=> 1
[6] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers_count
=> 0

Shouldn't .size just return what is in answers_count? Why is it not working like I expect? I can always just use answers_count, but I feel like there may be a bigger problem here that I would love to get to the bottom of.

marcamillion
  • 32,933
  • 55
  • 189
  • 380
  • `.size` giving you count from the loaded records in the memory. And it is `1` because in memory you have now `1`, as the partial rendering line shows in your question. `.count` will always hit the DB, as the answer is not persisted yet, it gives you `0`. Does it help? Btw, when you have the _cache_ set up, then use `answers_count` always, don't use the other 2 methods as u did. – Arup Rakshit Jun 20 '16 at 21:34
  • @ArupRakshit That's what I am realizing, but the actual documentation from Rails says that `.size` will give you the cached result -- which clearly isn't the case. – marcamillion Jun 20 '16 at 21:41
  • I think by _cahce_, they meant probably the already loaded records in memory. But not about your counter_cache columns really. Point me to that doc link please. – Arup Rakshit Jun 20 '16 at 21:44
  • @ArupRakshit Check it out here: http://guides.rubyonrails.org/association_basics.html (point 4.1.2.3) – marcamillion Jun 20 '16 at 23:05

0 Answers0