Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 eager loading of deep nested association

I am building a public activity stream which contains a stream of the following:

  1. User posted 3 minutes ago
  2. User starred a post

I am using the public_activity gem for achieving this.

My question is whether there is a way to use the includes for a polymorpic function.

The code that i am running currently is as follows:

#app/models/post.rb

class Post < ActiveRecord::Base

    include PublicActivity::Common

    attr_accessible :content, :visibility

    validates_presence_of :content

    belongs_to :postable, :polymorphic => true
    has_many     :stars

end

#app/models/star.rb
class Star < ActiveRecord::Base

  include PublicActivity::Common

  validate :duplicate_star

      belongs_to :user
  belongs_to :post

private
    def duplicate_star
 errors.add(:base, "Post already starred") if Star.exists?(:user_id => self.user, :post_id => self.post)
   end

end


#app/controllers/users_controller.rb
class UsersController < ApplicationController
  def index
    @post = Post.new
    @activities = PublicActivity::Activity.order("id desc").all.includes(:trackable, :owner)
  end
end

The trackable can be a post or a star. I have render functions for displaying both. The problem is, if I try to output something like {user} starred {postcontent}, it does it this way:

activity.trackable.post.content

So this results in multiple queries, each time it finds a post. How do I tackle this problem/situation?

Thanks in advance.

like image 623
swaroopsm Avatar asked Jun 11 '13 11:06

swaroopsm


1 Answers

Are you not able to use the standard eager loading syntax?

@activities = PublicActivity::Activity.order("id desc").includes(:owner, :trackable => {:post => :content})
like image 184
Carlos Drew Avatar answered Nov 05 '22 23:11

Carlos Drew