我有一個表像這樣的「捆綁」Rails的加入 - 在同年齡組選擇用戶
Bundle.joins("inner join users on users.id=bundles.user_id").where("users.first_name = ?", first_name).where("users.last_name = ?", last_name).where("users.age_group = ?", age_group)
所以,在這裏,我們正在根據匹配用戶的所有包(由表中的非列比較) 。
這裏,firstname,lastname是'users'表上的列。
但age_group不是列,它是從dob(column)計算的模型方法。
如何做到這一點?
AGEGROUPS = { 'teen' => 13..18, 'aboveteen' => 19..30, 'above30' => 31..40 }
def age_group #a model method of user.rb
age = get_age(self.birthdate)
User::AGEGROUPS.each do |g|
if age.between?(g[1].first, g[1].last)
return g[0]
end
end
end
def get_age
return unless birthdate
now = Time.now.utc.to_date
now.year - birthdate.year - (birthdate.to_date.change(:year => now.year) > now ? 1 : 0)
end
讓我知道更多的信息。
那麼你如何計算你的'age_group'?你將不得不用SQL語句重寫它。 – 2014-09-03 09:37:55
@MarekLipka你可以請你這樣做。我不知道該怎麼做。我會用年齡組模型方法更新問題。 – user2349115 2014-09-03 09:38:42