开发者

Rails and date: get profiles with related ages

Hy,

I have a profile x, that has a born_date and then i want to get all the profiles that has more or less 5 years.

If profile x has 20 years, i want every开发者_开发知识库 profile that has between 15 and 25 years.

Here i need some date calculations and i dont really know how to do it. You have some ideas? ;)


Date calculations in Rails is pretty easy, with the helpers that you get through ActiveSupport::CoreExtensions::Numeric::Time

You can get a profile within 5 years in either direction with a simple query with conditions, using some date math:

x = Profile.first 
prof_five_years = Profile.find(:all, 
                               :conditions => ['born_date > ? and born_date < ?',
                                               x.born_date - 5.years, 
                                               x.born_date + 5.years])


I would suggest that you also have a look at the searchlogic gem. http://github.com/binarylogic/searchlogic


select p1.* from profile p1, profile p2 where p1.born_date <= DATE_ADD(p2.born_date, interval 5 years) and p1.born_date >= DATE_SUB(p2.born_date, INTERVAL 5 year) and p1.id=x.id

if you don't want X profile then try

select p1.* from profile p1, profile p2 where p1.born_date <= DATE_ADD(p2.born_date, interval 5 years) and p1.born_date >= DATE_SUB(p2.born_date, INTERVAL 5 year) and p1.id=x.id and p2.id !=x.id

where x.id is a profile of user's to match

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜