为什么.size方法不响应存储在counter_cache中的实际值?

时间:2016-06-20 21:16:12

标签: ruby-on-rails rails-activerecord ruby-on-rails-5 counter-cache

我有DECLARE @SqlScript AS Varchar(max) DECLARE @version AS Varchar(10) SET @version = '20160620' SET @SqlScript = ' DECLARE @colTableUP TABLE ( x varchar(50) ,y varchar(50) ,z varchar(50) ) INSERT INTO @colTableUP SELECT x, y, z FROM [dbo].[Table1_' + @version + '] UNION ALL SELECT x, y, z FROM [dbo].[Table2_' + @version + '] UNION ALL SELECT x, y, z FROM [dbo].[Table3_' + @version + '] UNION ALL SELECT x, y, z FROM [dbo].[Table4_' + @version + ']' --SELECT @SqlScript EXEC (@SqlScript); 模型Question& has_many :answers

在我的# answers_count :integer default(0)型号上,我有:

Answer

在我的belongs_to :question, counter_cache: true 页面上,当显示我的Question#Show部分内容时,我构建了一个答案实例,以便包含在表单中,如下所示:

Answer#Form

在下面,我显示当前与此问题相关的答案数。它不应该包含我在表单中<%= render partial: "answers/form", locals: {answer: @question.answers.build(user: current_user)} %> 中的那个未经包含的答案,但确实如此。

这是built

的值
@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>

这给了我想要的结果,但它也做了我想避免的数据库查询。对[4] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers.count CACHE (0.0ms) SELECT COUNT(*) FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 51]] => 0 的调用似乎达到了缓存的值,但它给了我错误的值,如下所示。

size

[5] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers.size => 1 [6] pry(#<#<Class:0x007fadab5f4d48>>)> question.answers_count => 0 不应该只返回.size中的内容吗?为什么它不像我期望的那样工作?我总是可以使用answers_count,但我觉得这里可能存在一个更大的问题,我希望能够深入到底。

0 个答案:

没有答案