Question

My question is very straight and simple. I'm using Rails 3.2.13 and Ruby 2.0.0 for developing a Web application. I have a query in my questions_controller,

@questions = Question.where("parent_id =? and question_type_id = ?",57,12) which generates the below result.

[#<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">]

Then, if I take @questions.count, it is fine and I'm getting 1 as the count as I could find this is an array object also.

But, for @questions = Question.find_by_parent_id_and_question_type_id(57,12), it returns

#<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">

and when I did @questions.count OR @questions.length, it returns an error

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

OR

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

Can anyone help me to find out why this happens or how we can find total count or records from an active record object not through an array?

Thanks :)-

Was it helpful?

Solution

The find_by returns the single resulting object (or if the query returns more than one row, the first object of the result), not an Array containing the result.

When using Rails 3.X, you can use find_all_by, e.g. find_all_by_parent_id_and_question_type_id to get the Array you expected.

find_all_by will still work in Rails 4.0, but is deprecated. Using where is preferred in both versions of Rails. For your specific example, I like the following format:

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

See https://github.com/rails/activerecord-deprecated_finders for details.

OTHER TIPS

If you use .where and .count, you will get the proper query instead of counting the size of a returned array

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 

Rajesh ruby's .count or .length method can only apply on Array or Hash. You can't use that method on any ActiveRecord object

Here in your second query you are getting result of 1 object, so u can't use .count or .length in this case

Steve Wilhelm is right. We have several ways to do it,

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

OR

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

OR directly take the count using,

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

Thank you all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top