我试图让这个嵌套的 if 语句起作用,但我的语法错误,我无法理解。我在 Rails 4 应用程序上有一个搜索框和一个排序下拉列表。在搜索结果页面上,我想根据用户在排序下拉列表中选择的内容对产品列表进行排序。如果用户没有输入搜索词,我希望显示一条消息。这是我的 Controller 代码。
如果我删除条件并只显示默认排序,搜索结果页面显示正常,所以错误在 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
最佳答案
你在这里想要的是一个 case
语句,一个来自其他语言(如 JavaScript 和 C)的 switch:
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
在 Ruby 中,case
语句的结果可用于分配给一个变量,这样就消除了很多 @listings =
重复。 if
也是如此。
您在此处进行比较的内容似乎异常具体。如果您有一个用于选择排序顺序的下拉列表,它们应该在内部使用更简洁的值,例如 plh
表示“价格 - 从低到高”,甚至是数字代码。这意味着即使更改了措辞,您的代码仍然有效。
关于ruby-on-rails - Ruby - 嵌套 IF 语句语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26261527/