所以我正在構建一個匹配用戶的應用程序。用戶模型有3個屬性(即有關我的問題反正:gender:string
,looking_for_men:boolean
,looking_for_women:boolean
複雜的範圍,Rails 3
目前我有一個方法,在我的模型,像這樣:
def browse
if self.looking_for_men == true && self.looking_for_women == true
if self.sex == "Male"
User.where("looking_for_men = ?", true)
elsif self.sex == "Female"
User.where("looking_for_women = ?", true)
end
elsif self.sex == "Male" && self.looking_for_men == true
User.where("looking_for_men = ? AND sex = ?", true, "Male")
elsif self.sex == "Female" && self.looking_for_women == true
User.where("looking_for_women = ? AND sex = ?", true, "Female")
else
if self.sex == "Male"
User.where("looking_for_men = ? AND sex = ?", true, "Female")
elsif self.sex == "Female"
User.where("looking_for_women = ? AND sex = ?", true, "Male")
end
end
end
這是相當混亂,如你可以告訴我們有沒有辦法清理這個問題,並把它變成一個範圍,比如說我是一個男性用戶,並且我正在尋找女性,它只會返回在我查詢時正在尋找男性的女性像這樣:
@users = User.all.browse
我喜歡這個。爲了可讀性,我會重命名範圍'looking_for_men'和'looking_for_women'(與布爾值相沖突);但那不是真的需要。 – nathanvda