【问题标题】:Taking count of records of an active record object in Rails在 Rails 中计算活动记录对象的记录
【发布时间】:2013-11-30 08:44:56
【问题描述】:

我的问题非常直接和简单。我正在使用 Rails 3.2.13 和 Ruby 2.0.0 开发 Web 应用程序。我的 questions_controller 中有一个查询,

@questions = Question.where("parent_id =? and question_type_id = ?",57,12) 生成以下结果。

[#<Question id: 58, description: "Explian Pointers", question_type_id: 12, parent_id: 57, created_at: "2013-11-21 06:38:58", updated_at: "2013-11-21 06:38:58">]

然后,如果我采用 @questions.count,那很好,我会得到 1 作为计数,因为我发现这也是一个数组对象。

但是,对于@questions = Question.find_by_parent_id_and_question_type_id(57,12),它返回

#<Question id: 58, description: "Explian Pointers", question_type_id: 12, parent_id: 57, created_at: "2013-11-21 06:38:58", updated_at: "2013-11-21 06:38:58">

当我执行 @questions.count 或 @questions.length 时,它会返回错误

undefined method `length' for #<Question:0x00000006496b90>

或

undefined method `count' for #<Question:0x00000006496b90>

谁能帮我找出为什么会发生这种情况,或者我们如何不通过数组从活动记录对象中找到总计数或记录?

谢谢:)-

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord count ruby-2.0


    【解决方案1】:

    find_by 返回单个结果对象(或者如果查询返回多行,则返回结果的第一个对象),而不是包含结果的数组。

    使用 Rails 3.X 时,您可以使用 find_all_by,例如find_all_by_parent_id_and_question_type_id 得到你期望的数组。

    find_all_by 仍可在 Rails 4.0 中使用,但已弃用。在两个版本的 Rails 中都首选使用where。对于您的具体示例,我喜欢以下格式:

    Question.where(:parent_id => exam_Question.id).where(:question_type_id => 12).count
    

    详情请见https://github.com/rails/activerecord-deprecated_finders。

    【讨论】:

    • 你也应该在 Rails 3 中使用where。
    【解决方案2】:

    如果您使用.where 和.count,您将获得正确的查询,而不是计算返回数组的大小

    Question.where(parent_id: 57, question_type_id: 12).count
    
    # => SELECT COUNT(*) FROM "questions" WHERE "questions"."parent_id" = 57 AND "questions"."question_type_id" = 12 
    

    【讨论】:

      【解决方案3】:

      Rajesh ruby​​ 的 .count 或 .length 方法只能应用于 Array 或 Hash。您不能在任何 ActiveRecord 对象上使用该方法

      在您的第二个查询中,您得到 1 个对象的结果,因此在这种情况下您不能使用 .count 或 .length

      【讨论】:

        【解决方案4】:

        史蒂夫·威廉是对的。我们有几种方法可以做到这一点,

        @questions = Question.find_all_by_parent_id_and_question_type_id(57,12)
        @count = @questions.count => 1
        

        或

        @questions = Question.where("parent_id =? and question_type_id = ?",exam_Question.id,12)
        @count = @questions.count => 1
        

        或直接使用计数,

        @questions = Question.count(:conditions => {:parent_id => exam_Question.id, :question_type_id => 12})
        @questions => 1
        

        谢谢大家。

        【讨论】:

          猜你喜欢
          • 2011-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-30
          • 1970-01-01
          • 1970-01-01
          • 2012-06-20
          • 1970-01-01
          相关资源
          最近更新 更多