Reputation: 2323
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
Reputation: 3709
You can also use this simple query...
@result=current_user.results.find_by_test_id(:test_id)
Upvotes: 0
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
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
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