1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to simplify big conditions

Discussion in 'Programming/Internet' started by Nilay Singh, Sep 12, 2018.

  1. Nilay Singh

    Nilay Singh Guest

    I have five dropdowns, and I need to put conditions on each of them. My code is:

    def search(search, compare, year, rain_fall_type)
    if search == 'All'
    if rain_fall_type == 'All'
    all
    else
    if year == 'All'
    if rain_fall_type == "None"
    where('Sector = ? OR Sector = ? OR Sector = ?', "Primary", 'Secondary', 'Tertiary').order('id')
    else
    # all
    where(Sector: rain_fall_type).order('id')
    end
    else
    if rain_fall_type == "All"
    order("#{year} ")

    elsif rain_fall_type == "None"
    where('Sector = ? OR Sector = ? OR Sector = ?', "Primary", 'Secondary', 'Tertiary').order('id')
    else
    where(Sector: rain_fall_type).order("#{year} ")
    end
    end
    # where(Year: year).order("#{rain_fall_type} ")
    end
    elsif compare != "None"
    if year == 'All'
    where('Sector = ? OR Sector = ?', rain_fall_type, compare).order:)id)
    else
    where('Sector = ? OR Sector = ?', rain_fall_type, compare).order:)id)
    end
    else

    if rain_fall_type == 'All'
    all.order('id')
    else
    if year == 'All'

    if rain_fall_type == "None"
    where('Sector = ? ', search).order('id')
    else

    where('Sector = ? ', rain_fall_type).order('id')
    end
    else

    if rain_fall_type == "None"

    if search == "All"
    where('Sector = ? ', search).order('id')
    else
    where('Sector = ? ', search).order('id')
    end
    else
    # all
    where('Sector = ? ', rain_fall_type).order('id')
    end
    end
    end
    end
    end


    It has many if and else. I am trying to minimise the conditions. What can be the best way to shrink this code? Someone suggested that I should use switch case instead. Should I use it? If so, how?

    Login To add answer/comment
     

Share This Page