JoeGH
(Joseph Crocetta)
January 20, 2016, 4:21pm
1
Can’t seem to get past this.
Seems that the result is always false.
It must be something so simple.
Any help?
(menu_type == 1) ? (redirect_to catering_path) : (redirect_to deli_path)
I tried with strings, 3 equal signs just in case LOL, with/without parenthesis, with/without returns
I even tried:
redirect_to catering_path if menu_type == 1
current (simplified) whole method here:
def create
menu_type = params[:menu_type_id]
@menu_item = MenuItem.new(menu_item_params)
@menu_item.save
(menu_type == 1) ? (redirect_to catering_path) : (redirect_to deli_path)
end
Thank You.
JoeGH
(Joseph Crocetta)
January 20, 2016, 4:59pm
2
Sorry for the foolish question.
I took a step back and took a breath.
Now I’m using
redirect_to request.referrer
and that works just fine for my scenario.
I’m curious though, could there be any reason for why this would not be an acceptable solution according to Thoughtbot best practices?
Thanks again and sorry for any inconvenience.
1 Like
lenart
(Lenart Rudel)
January 29, 2016, 9:07am
3
It’s probably because params[:menu_type_id] is in fact a string “1” not an integer 1.
andyw8
(Andy Waite)
January 29, 2016, 10:33am
4
Yes, params[]
values are always strings. Often this doesn’t matter, e.g. you can call Product.find
and pass an ID as a string.
But in this case where you’re doing a comparison, you would need to write menu_type == "1"
or menu_type.to_i == 1
.
(To confuse things, 1 == "1"
would return true in JavaScript but false in Ruby!).
To debug this kind of problem, I find it useful to set a breakpoint using Pry, and then call menu.inspect
to check the variable’s type.
JoeGH
(Joseph Crocetta)
January 29, 2016, 12:58pm
5
Another thing to read up on? Pry? I have like 10 tabs of things I want to read. Just kidding… Thanks.
Chadh13
(Chad Heinen)
January 29, 2016, 3:31pm
6
Andy, when you say breakpoint are you referring to something like you find at this post under the Figuring out how a method was called section?
@JoeGH ,
Pry is an excellent tool for stopping application execution in a spot where you’re curious about what’s happening!
We’d also recommend that you avoid using the ternary operator test ? if_true : if_false
, as it’s somewhat confusing to follow, and hides the branching nature of your code. The more verbose multi-line if else end
statements make it very clear to a reader (who might be you in the future!) that there’s different paths in your code.