简体   繁体   中英

How to write this nifty way?rails

I am trying to write this code in more elegant way in my view. Can you help me?

<%= if category.photo.present?
    category.photo
    else 
    category.img_parse_url
end %>

category.photo might be nil or empty string)

You can use try method which is not needed here as @tadman pointed out, besides, as you wrote below in comment photo can be an empty string (I wrongly assumed it cannot be) so those two versions will return an empty string if category.photo is just an empty string:

<= category.try(:photo) || category.img_parse_url %>

And without try :

<= category.photo || category.img_parse_url %>

or move that to model.

edit:

If the photo can be an empty string then maybe use ternary operator?

<%= category.photo.present? ? category.photo : category.img_parse_url %>

or use the presence method:

<%= category.photo.presence || category.img_parse_url %>

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