[英]Rails model query with many optional params
用戶想要按屬性搜索和/或排序結果。 這是一些示例請求
/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
請記住,諸如where
和order
類的查詢方法是要鏈接的。 您要做的是從基本查詢開始(例如在所有情況下都使用Post.where(common)
),然后有條件地鏈接其他方法:
def index
common = Hash.new
common["user_id"] = current_user.id
@vacancies = Post.where(common)
if params[:order]
@vacancies = @vacancies.order(title: params[:order].to_sym)
end
if params[:title]
@vacancies = @vacancies.where("LOWER(title) LIKE ?", params[:title])
end
end
PS您的原始代碼為.order("title #{params[:order]}")
。 這非常危險,因為它使您容易遭受SQL注入攻擊。 根據經驗,在將結果傳遞給數據庫時, 切勿將字符串連接( #{...}
)與最終用戶獲得的值一起使用。 因此,我將其更改為.order(title: params[:order])
。 Rails將使用此哈希值構造一個安全的查詢,因此您不必擔心注入攻擊。
您可以在Ruby on Rails官方安全指南中閱讀有關Rails中SQL注入攻擊的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.