2

I have a few scenarios where I would like to do as little DB calls as much as possible via eager loading, but I have not been able to do it well.

Given the 2 scenarios below, how can i change my RABL to do as little calls as possible?


OBJECT MODEL:

Posts 
-> belongs_to user
-> has_many: Comments 
     -> Comment belongs_to user
-> has_many: Tags
     -> Tag belongs_to user

RABL (Both of these will cause the DB to do many individual calls)

node(:comments) do |p|
  p.filtered_comments(@user)
end

child :tags do
  attribute :text
  child :users do
     attribute :nickname
  end
end

CONTROLLER QUERY

Post.includes(user, comments, tags)...

POST.RB

def filtered_comments
    comments = self.comments.where(:blocked=>false).all
    json = Rabl::Renderer.json(comments, 'comments/list', view_path: 'app/views')
    JSON.parse(json).map do |c|
      c['comment']
    end
end
meow
  • 27,476
  • 33
  • 116
  • 177

1 Answers1

1

Usually, the controller defines the object that rabl iterates across, say a @user.

So in the controller, I normally eager-load relations, such as permissions and articles like so: @user = User.find(1).includes(:permissions, :articles), and respons with said user object like this: respond_with @user.

Then, in the rabl file, I have something like:

# some_file.json.rabl
object @user
child :permissions do
  attributes :name
end
node :first_article do |u|
  u.articles.first
end

This fixed my version of the chatty view files.

ekampp
  • 1,904
  • 18
  • 31