0
用戶想要通過屬性進行搜索和/或對結果進行排序。以下是一些示例請求帶有許多可選參數的Rails模型查詢
/posts?order=DESC&title=cooking
/posts?order=ASC
/posts?title=cooking
如何有條件地鏈接這些選項以形成查詢?
到目前爲止,我有一個非常難看的方法,很快就會變得難以維護。
def index
common = Hash.new
common["user_id"] = current_user.id
if params[:order] && params[:title]
@vacancies = Post.where(common)
.where("LOWER(title) LIKE ?", params[:title])
.order("title #{params[:order]}")
elsif params[:order] && !params[:title]
@vacancies = Post.where(common)
.order("title #{params[:order]}")
elsif params[:title] && !params[:order]
@vacancies = Post.where(common)
.where("LOWER(title) LIKE ?", params[:title])
end
end
優秀的答案。一件小事,必須將'順序'轉換爲符號才能正常工作:'params [:order] .to_sym'。錯誤只表示:asc和:desc被接受的方向。 – frostbite
好的。我已經更新了我的答案。 –