Monday, December 5, 2011

Rails Include vs Joins


Include & Join both are similar in the way, as because both are use to find the associated table value with single query. This is really very confusing what should we use :include or :joins. There is very nice article by railscasts also we can check the find method of active record.

I have conclude few point which make easier to take decision.

:include
- It implies eager-loading on associations.
- It fetch all the class record or object attributes and keep it into the memory.
- It fetch all the associated object attributes with select option.
- It will be useful if want to use associated object attribute on view.
- By default it will do 'LEFT OUTER JOIN', which shows all the record from table.
eg.

As :include will do eager-loading, when try to fetch the user record then it will not raise another query.


:joins
- It actually do an 'INNER JOIN' which filters the rows that don't have association.
- It is for joining association names in different ways and joins the relevant tables.
- Every time it make a separate query to fetch the associated object attribute values.
eg.

As :joins is not doing eager-loading, when try to fetch the user record from comment it will raise another sql query.



No comments:

Post a Comment