简体   繁体   中英

Rails: Conditional statement with && and ||

I currently have this:

<% if h.ab_template.AB_filterParent == 0 && h.status != 'geo_enabled' %>

What I'd like to do is say whether if h.ab_template.AB_filterParent == 0 || nil. How would I do that?

I tried this but it wasn't working:

    <% if (h.ab_template.AB_filterParent == 0 || nil) && h.status != 'geo_enabled' %>

Would love to know what I've mistyped or implemented incorrectly!

Cheers

If you are sure that h.ab_template.AB_filterParent will always be a number (can be wrapped by quotes), then you can try following

<% if h.ab_template.AB_filterParent.to_i == 0 && h.status != 'geo_enabled' %>

else, if there is a possibility that h.ab_template.AB_filterParent can be something like "abc" , "0asd" etc then try:

<% if (h.ab_template.AB_filterParent.nil? || h.ab_template.AB_filterParent == 0) && h.status != 'geo_enabled' %>

Generally nil and zero shouldn't mean the same thing. Try to eliminate the possibility of AB_filterParent being nil before you hit this code, by assigning a default value of zero in your migration table. I don't know how your model is so I can't even show an example of how to do it. The main problem of using to_i == 0 is that it only works if AB_filterParent is either an integer or nil.

0.5.to_i == 0
"asdasd".to_i == 0

So it's odd.

Another way is to have it initialized in an action or other model method or even after_create callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM