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. I have a search box on a Rails 4 app and a sort dropdown. 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.
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:
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. Same goes for an 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. That means if the phrasing is changed your code still works.
我会改变你的下拉值,如price asc
, price desc
, arrival_date asc
(不知道随机洗牌),然后你可以使用。
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
链接地址: http://www.djcxy.com/p/25654.html
上一篇: 包含从1到N的数字的数组
下一篇: 嵌套的IF语句语法