I watched this rails cast http://railscasts.com/episodes/22-eager-loading but still I have some confusions about what is the best way of writing an efficient GET REST service for a scenario like this:
Let’s say we have an Organization table and there are like twenty other tables that there is a belongs_to and has_many relations between them. (so all those tables have a organization_id field).
Now I want to write a GET and INDEX request in form of a Rails REST service that based on the organization id being passed to the request in URL, it can go and read those tables and fill the JSON BUT NOT for ALL of those table, only for a few of them, for example let’s say for a Patients, Orders and Visits table, not all of those twenty tables.
So still I have trouble with getting my head around how to write such a
.find( :all )
sort of query ?
Can someone show some example so I can understand how to do this sort of queries?
You can include all of those tables in one SQL query:
Now when you do something like:
It will load the patients in-memory, since it already fetched them in the original query. Without
includes,@organization.patientswould trigger another database query. This is why it’s called “eager loading”, because you are loading thepatientsof the organization before you actually reference them (eagerly), because you know you will need that data later.You can use
includesanytime, whether usingallor not. Personally I find it to be more explicit and clear when I chain theincludesmethod onto the model, instead of including it as some sort of hash option (as in the Railscast episode).