mardi 30 juin 2015

Rails "includes" Method and Avoiding N+1 Query

I don't understand the Rails includes method as well as I'd like, and I ran into an issue that I'm hoping to clarify. I have a Board model that has_many :members and has_many :lists (and a list has_many :cards). In the following boards controller, the show method looks as follows:

def show
  @board = Board.includes(:members, lists: :cards).find(params[:id])
  ...
end

Why is the includes method needed here? Why couldn't we just use @board = Board.find(params[:id]) and then access the members and lists via @board.members and @board.lists? I guess I'm not really seeing why we would need to prefetch. It'd be awesome if someone could detail why this is more effective in terms of SQL queries. Thanks!

Aucun commentaire:

Enregistrer un commentaire