Friday, February 15, 2008

ActiveRecord tricks - :include and :select options

When I say something like:

Project.find(:all, {
:select => "projects.id, projects.name, tasks.id, tasks.owner",
:include => :tasks
})
The AR returns all fields from projects and tasks table. Whenever there is an :include option, it just ignores the :select options. To work around this, we can either specify the :join option like:

Project.find(:all, {
:select => "projects.id, projects.name, tasks.id, tasks.owner",
:join => "LEFT OUTER JOIN tasks ON projects.id = tasks.id WHERE projects.id = #{whatever}"
})

Or, we can specify the whole SQL like:
Project.find_by_sql("SELECT projects.id AS p_id, projects.name AS p_name, tasks.id AS t_id, tasks.owner AS t_owner
FROM projects LEFT OUTER JOIN tasks ON projects.id = tasks.id WHERE projects.id = #{whatever}")
We don't have to know a lot of SQL to write these work around solutions. Just look for the generated SQL query in the log file when you specified the :include option, copy that SQL, modify it and use it here.

No comments: