When you use find, you can include related objects with include so that
both objects get instantiated in the results, e.g. Foo.find(:all,
:include => :bar).
But when you use find_by_sql, is there a way to do this? You could
definitely write the find_by_sql SQL to join Foo and Bar tables:
Foo.find_by_sql(“SELECT foo., bar. from foo, bar where foo.bar_id =
bar.id”)
But is there a way to instantiate not just the Foo object but also the
Bar object in the results that come back?
When you use find, you can include related objects with include so that
both objects get instantiated in the results, e.g. Foo.find(:all,
:include => :bar).
But when you use find_by_sql, is there a way to do this? You could
definitely write the find_by_sql SQL to join Foo and Bar tables:
Foo.find_by_sql(“SELECT foo., bar. from foo, bar where foo.bar_id =
bar.id”)
But is there a way to instantiate not just the Foo object but also the
Bar object in the results that come back?
Yes: Install the AR mod at http://mrj.bpa.nu/eager_custom_sql.rb ,
add the include option, then write your SQL using the tn_rm field
alias pattern used by Rails’ eager loading.
–
We develop, watch us RoR, in numbers too big to ignore.