Query has_many through association Rails -


i have has_many though association this:

user.rb has_many :memberships, :dependent => :destroy  has_many :groups, :through => :memberships  group.rb has_many :users, :through => :memberships has_many :microposts   membership.rb belongs_to :user belongs_to :group 

first need know query groups of user, after need way show microposts of groups. possible 1 query information?

thanks lot!

to user's groups:

some_user = user.find(some_id) some_user.groups 

to microposts, do:

some_user.groups.each |group|   puts group   puts group.microposts end 

however, cause separate query generated collect microposts of each group. can fixed eager-loading microposts using includes:

some_user.groups.includes(:microposts).each |group|   puts group   puts group.microposts end 

now 2 queries generated - 1 fetch groups, , 1 fetch all microposts associated these groups. behind scenes, activerecord match microposts correct group, , return them accordingly when calling .microposts on group.

to microposts hash, can use each_with_object collect them:

@group_microposts = some_user.groups.includes(:microposts).                               each_with_object({}){|group, h| h[group] = group.microposts} 

this return hash in form { group => microposts }.

to them array, could do:

@microposts = some_user.groups.includes(:microposts).map(&:microposts).flatten 

however, there more efficient way if don't need group information @ all:

@microposts = micropost.joins(:group => :users).where(:users => {id: some_user.id}) 

this second method faster because of 2 reasons - requires single query (no eager loading needed) , db lookup more efficient since can use available indices perform necessary joins rather filter against literal integer list (which can slow list gets larger).


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -