Joe Half Face
Joe Half Face

Reputation: 2323

Where method if condition is false

Does it return empty array or nil if condition is false? For example:

@result=Result.where(:test_id=>test_id, :user_id => current_user.id).first

if there is no result with such test_id and user_id.

I just don't get, I thought first option, but this returns nil.

Upvotes: 1

Views: 109

Answers (4)

Thaha kp
Thaha kp

Reputation: 3709

You can also use this simple query...

@result=current_user.results.find_by_test_id(:test_id)

Upvotes: 0

Andy Hayden
Andy Hayden

Reputation: 375377

Your variable is constructed in two parts, the first part returns an ActiveRecord::Relation (which is essentially an array):

 @result_array = Result.where(:test_id=>test_id, :user_id => current_user.id)

 > @result_array.class
  => ActiveRecord::Relation

which is empty (shows as []) if there are no results.

The second returns the first item, or (if it's the empty array) nil:

> (1..10).first
 => 1

> [].first
 => nil

@first_or_nil = @result = @result_array.first

I recommend typing these type of commands in the rails console to see what the results.

Upvotes: 3

nikolayp
nikolayp

Reputation: 17919

Thy to use #bang with method .first! For example:

@result=Result.where(:test_id=>test_id, :user_id => current_user.id).first!

It should return the first element whit ruby will meet in table "results".
It should help.

Upvotes: 0

Ganesh Kunwar
Ganesh Kunwar

Reputation: 2653

For your problem you may use like this code.

@result=Result.where(:test_id=>test_id).(:user_id => current_user.id).first

Upvotes: 0

Related Questions