ruby on rails - Best way to find Users with certain associations -


lets have user model , each user has association called user_logins created every time login, storing information login.

what need find users have 5 user_login records, fifth record created today.

something this:

users = user.all.where(user_logins_count == 5, user_login.last.created_at == today) 

user_logins_count counter cache have set up.

of course code brutal, it'll elaborate on i'm trying achieve.

pg error

rake aborted! activerecord::statementinvalid: pg::undefinedtable: error:  missing from-clause entry table "last " line 1: ...n_logins_count" = 5 group humans.id having max(human_logi...                                                              ^ 

new code:

humans = user.humans.joins(:human_logins).where(human_logins_count: 5)         .group('humans.id')         .having('max(human_logins.created_at) >= ?', date.today) 

you can define scope inside user class:

class user   scope :logged_in_a_lot_today, ->     joins(:user_logins).where(user_logins_count: 5)       .group('users.id')       .having('max(user_logins.created_at) >= ?', date.today)   end end 

now can these users with:

user.logged_in_a_lot_today 

since it's defined scope, can add more conditions if you'd to:

user.logged_in_a_lot_today.where(name: 'john doe') 

note idea set partial index (if database supports it) on users have user_logins_count of 5.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -