How to use preload in Ruby on Rails

To avoid problem N + 1 in RoR, we can use preload, preload will load all association records using another sql query.

Example: we have model User, Post and Comment with relation:

User has_many Posts

Post has_many Comments

Now you want to show all male users associated with their posts and comments.

If you can do like this

User.preload(posts: :comments).where(gender: :male)

It will generate 3 sql query.

1. For load all user with gender male

2. Load all posts with user_id in id of first query

3. Load all comments with post_id in id of second query

So it only take 3 query for all users instead of 3 query for each users. It will save a lot of time

That’s all.

 

Advertisements

Get facebook picture using Koala gem

This article is about loading facebook images using Koala GEM

Install Koala GEM

gem install koala

or add to Gemfile

gem 'koala'

To load pictures of facebook user, you have to get user access token, you can access https://developers.facebook.com/tools/explorer/ then click GET TOKEN

To read more about how to get photos from Facebook document

https://developers.facebook.com/docs/graph-api/reference/user/photos

https://developers.facebook.com/docs/graph-api/reference/v2.7/album/photos

You can get photos by specific album, or you can get photos from all albums. I will demo get photo from all albums. Normally, when you get photos, fb will return all photos include your tag photos. So if you want to get only your uploaded photos, you can add params type = ‘uploaded’. Notice that: you only can get maximum 25 images per request.

class LoadFbImage
  def initialize(token)
    @fb_graph = Koala::Facebook::API.new(token)
  end

  def get_fb_photos(page = nil)
    if page.present?
      data = @fb_graph.get_page(page)
    else
      data = @fb_graph.get_connections('me', 'photos', type: 'uploaded',
                        fields: 'images', limit: 25)
    end

    {
      pictures: data.map{ |p| p['images'].first["source"] },
      # a list of pictures url
      # fb will return images with many size, so I only get first result
      next_page_params: data.next_page_params
      # next_page_params needs when want toload more image
      # next_page_params will be nil in last page
    }
   end
end

if you use Graph API, you can write FQL Query like

GET /{user-id}/photos?type=uploaded

if you want to load images that belongs to specific album, you can write

GET /{album-id}/photos?type=uploaded

That’s all.