views:

80

answers:

2

Why is the second if statement failing in the following code block? The output from the console indicates that the private parameter is 0, so it should be passing? The private parameter is from a checkbox in the new form, that I'm using to set a boolean field in the model.

if (((params[:note])[:text]) != "")
  logger.debug("passed first test")
  logger.debug(((params[:note])[:private]))
  if (((params[:note])[:private]) == 0)
    logger.debug("passed second test")
  end
end

console output

passed first test
0
Completed in 61ms (DB: 1) | 302 Found [http://localhost/notes]

Thanks for reading.

+1  A: 

In cases where two expressions print the same, but aren't equal, you usually have different types. For example "0", :"0" and 0 both print as 0, but aren't actually equal to each other.

logger.debug(params[:note][:private].inspect) should give you more meaningful output, indicating the type of the object as well as the contents (i.e. if it's a string it's surrounded by quotes, if it's a symbol it starts with a colon, etc.).

The values in params are generally strings, so the value of params[:note][:private] is very probably "0", not 0.

sepp2k
+4  A: 

Form fields are submitted as strings so params[:notes][:private] will actually contain "0" not 0.

You could use either params[:notes][:private] == "0" or params[:notes][:private].to_i == 0 to get the comparison you're after.

If you want to treat non-integer values (including empty strings and missing values) differently from 0, you should not use String#to_i. I would recommend checking the String value in these cases.

You can use Object#inspect (as mentioned by @sepp2k) and Object#class when debugging to get a better idea of what types things are. When using script/console, I find ap (or pp) to be rather handy.


A side note: In Ruby you don't need so many parentheses. Here's the your example after a little bit of cleanup:

unless params[:note][:text].blank?
  logger.debug "passed first test"
  logger.debug params[:note][:private].inspect
  if params[:note][:private].to_i == 0
    logger.debug "passed second test"
  end
end
Jason Weathered
Thanks for your answer. Thanks also for your side note, I'm pretty new to RoR, my code looks a lot nicer now!
ben
I wouldn't just throw a `params[:note][:private].to_i == 0`. Try `nil.to_i` or `"Not a number".to_i`, it may cause some headaches in the future
Chubas
@Chubas Yes, anything not parsable as an integer will give `0` as the result. This is worth noting.Generally for numeric parameters, one is interested in if something is non-zero or not.
Jason Weathered