0

How to correctly check value in db: in table i have field add_after_sign_in which is boolean, by default it is false... but how to check if it is not empty and not true, then select such rows: i try:

litem = LineItem.find(:all, :conditions => {:cart_id => cart_id && !:add_after_sign_in })

but in litem there are no such records... why? Simple how to check table row value on non-true?

2
  • rails version?? so only when add_after_sign_in = false? Commented Jan 14, 2013 at 19:54
  • @tokland yes, only if false Commented Jan 14, 2013 at 20:03

3 Answers 3

1

conditions is a Hash. You are only messing up with the syntax. Try this one:

litem = LineItem.find(:all, 
  :conditions => {:cart_id => cart_id, :add_after_sign_in => [nil, false]})
Sign up to request clarification or add additional context in comments.

2 Comments

This method is deprecated in newer versions of Rails. where is the appropriate scoping method going forward.
OP, you say you didn't want NULL values, did you?
1

You cannot use symbols like this (but note that you can do similar things with squeel and Rails 3).

I'd write (note that it's line_items, it's a collection):

line_items = LineItem.where(:cart_id => cart_id, :add_after_sign_in => false)

However, with a sound model structure and named scopes you should be able to write more declarative code:

line_items = Cart.find(cart_id).line_items.without_add_after_sign_in

4 Comments

Always be careful to handle ActiveRecord::RecordNotFound exceptions when using find.
@Valdis: You can decide to a) return an empty array, or b) raise an exception. Personally I'd prefer the method to blow up right away if non-existing IDs are being passed.
@tadman such code: litem = LineItem.find(:all, :conditions => {:cart_id => cart_id, :add_after_sign_in => [nil, false]}) didn't thrrow exception for me, or what>
find(:all) won't throw exceptions, but find(1) will.
1

You can also use where for a more readable syntax:

litem = LineItem.where(cart_id: cart_id, add_after_sign_in: [nil, false])

or, with scopes:

class LineItem
  scope :not_added_after_sign_in, where(add_after_sign_in: [nil, false])
  #...
end

litem = LineItem.where(cart_id: cart_id).not_added_after_sign_in

Edit: tweaked after tokland's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.