[英]Ruby - Nested IF statement syntax
我试图让这个嵌套的if语句工作,但我的语法错了,我无法弄明白。 我在Rails 4应用程序上有一个搜索框和一个排序下拉列表。 在搜索结果页面上,我想根据用户在排序下拉列表中选择的内容对产品列表进行排序。 如果用户没有输入搜索词,我想要显示一条消息。 这是我的控制器代码。
如果我删除条件并只显示默认排序,搜索结果页面显示正常,因此错误在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等其他语言切换 :
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
表示“价格 - 从低到高”,甚至是数字代码。 这意味着如果更改了措辞,您的代码仍然有效。
我会改变你的下拉值,如price asc
, price desc
, arrival_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.