[英]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.