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.