简体   繁体   English

Ruby - 嵌套的IF语句语法

[英]Ruby - Nested IF statement syntax

I'm trying to get this nested if statement to work but my syntax is wrong and I can't figure it out. 我试图让这个嵌套的if语句工作,但我的语法错了,我无法弄明白。 I have a search box on a Rails 4 app and a sort dropdown. 我在Rails 4应用程序上有一个搜索框和一个排序下拉列表。 On the search results page, I want to sort product listings based on what the user selects in the sort dropdown. 在搜索结果页面上,我想根据用户在排序下拉列表中选择的内容对产品列表进行排序。 If a user doesn't enter a search term, I want a message to display. 如果用户没有输入搜索词,我想要显示一条消息。 Here is my controller code. 这是我的控制器代码。

If I remove conditions and just display a default sort, search results page displays fine so the error is in the if statement syntax. 如果我删除条件并只显示默认排序,搜索结果页面显示正常,因此错误在if语句语法中。

def search
    if params[:search].present?

      if params[:sort] == "- Price - Low to High"
        @listings = ...
      elsif params[:sort] == "- Price - High to Low"
        @listings = ...
      elsif params[:sort] == "- New Arrivals"
        @listings = ...
      elsif params[:sort] == "- Random Shuffle"
        @listings = ...
      else
        @listings = ...
      end

    else
      flash[:notice] = "Please enter one or more search terms e.g. blue shirt."
    end

  end

What you want here is a case statement, a switch from other languages like JavaScript and C: 你想要的是一个case语句,从JavaScript和C等其他语言切换

def search
  if params[:search].present?
    @listings =
      case (params[:sort])
      when  "- Price - Low to High"
        ...
      when "- Price - High to Low"
        ...
      when "- New Arrivals"
        ...
      when "- Random Shuffle"
        ...
      else
        ...
      end
  else
    flash[:notice] = "Please enter one or more search terms e.g. blue shirt."
  end
end

In Ruby, the result of a case statement can be used to assign to a variable, so that eliminates a lot of the @listings = repetition. 在Ruby中, case语句的结果可用于赋值给变量,因此消除了很多@listings =重复。 Same goes for an if . 同样适用于if

The things you're comparing against here seem unusually specific. 你在这里比较的东西看起来异常具体。 If you've got a drop-down listing that's being used to choose sort order, they should have more succinct values used internally, such as plh to represent "Price - Low to High", or even numerical codes. 如果您有一个用于选择排序顺序的下拉列表,它们应该在内部使用更简洁的值,例如plh表示“价格 - 从低到高”,甚至是数字代码。 That means if the phrasing is changed your code still works. 这意味着如果更改了措辞,您的代码仍然有效。

I would change your drop down to have values like price asc , price desc , arrival_date asc (not sure about random shuffle) then you could use. 我会改变你的下拉值,如price ascprice descarrival_date asc (不确定随机shuffle),然后你可以使用。

def search
  if params[:search].present?
    sort_listings(params[:sort])
  else
    flash[:notice] = "Please enter one or more search terms e.g. blue shirt."
  end
end

def sort_listings(sort)
  @listings ||= ...
  @listing.order(sort)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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