2014-09-03 41 views
0

我有一個表像這樣的「捆綁」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 

讓我知道更多的信息。

+0

那麼你如何計算你的'age_group'?你將不得不用SQL語句重寫它。 – 2014-09-03 09:37:55

+0

@MarekLipka你可以請你這樣做。我不知道該怎麼做。我會用年齡組模型方法更新問題。 – user2349115 2014-09-03 09:38:42

回答

1

這種嘗試它的語句之間:

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.birthday BETWEEN ? AND ?", begin_birthday(age_group), end_birthday(age_group) 

和兩個附加的方法來計算第一和相應年齡組的最後一年。 這樣begin_year('teen')= 13等等。

def end_birthday(age_group) 
    years = AGEGROUPS[agegroup].first 
    now = Time.now.utc.to_date 
    Date.new(now.year - years, now.month, now.day) 
    end 

    def begin_birthday(age_group) 
    years = AGEGROUPS[agegroup].last 
    now = Time.now.utc.to_date 
    Date.new(now.year - years, now.month, now.day) 
    end 
+0

謝謝,但在這裏,年齡是計算值。生日是領域。你能否更新答案? – user2349115 2014-09-03 09:58:46

+0

你如何計算get_age(生日)?我們需要以某種方式扭轉這個功能。 – irene 2014-09-03 10:06:31

+0

使用get_age函數更新的問題。 – user2349115 2014-09-03 10:08:43