Forum: Ruby on Rails Creating an escaped JOIN?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2008-10-26 10:21
Hi,

When creating a custom find for a model, with AR it is possible to do
something like:

:conditions => ['user_id = ?', params[:id]]


However, I would like to know if it is possible to do the same when
specifying a JOIN:

:joins => ['LEFT OUTER JOIN orders ON (items.order_id = orders.id AND
orders.user_id = ?', params[:id]]

I tried the above expression, but unfortunately, Rails didn't replace
the question mark with its escaped value.

Any idea if this is possible? I need to move some filtering from the
WHERE clause into the ON clause and have it all escaped.
7223c62b7310e164eb79c740188abbda?d=identicon&s=25 Xavier Noria (fxn)
on 2008-10-26 14:38
(Received via mailing list)
On Sun, Oct 26, 2008 at 10:21 AM, Fernando Perez
<rails-mailing-list@andreas-s.net> wrote:

> :joins => ['LEFT OUTER JOIN orders ON (items.order_id = orders.id AND
> orders.user_id = ?', params[:id]]

Placeholders are not supported there indeed.

You cannot work with regular AR association API calls right? For
example:

   # untested
   user = User.find(params[:id])
   items = user.orders.map(&:items).flatten.uniq

or say:

   # untested
   items = Item.all(
     :conditions => {'users.id' => params[:id]},
     :joins => {:order => :user}
   )

If not, you can still extract an integer from params[:id] and safely
interpolate. That's easy with Integer() or #to_i.

-- fxn
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2008-10-26 14:46
(Received via mailing list)
On Oct 26, 1:37 pm, "Xavier Noria" <f...@hashref.com> wrote:
>    # untested
>
> If not, you can still extract an integer from params[:id] and safely
> interpolate. That's easy with Integer() or #to_i.
>
and more generally the connection object's quote method (and variants)
are useful. See also the sanitize_sql method.

Fred
059ed46172a087063ce26250e44c8627?d=identicon&s=25 Fernando Perez (fernando)
on 2008-10-26 14:49
Hi Fred,

sanitize_sql is the way to go, then I simply evaluate what it spits me
out inside my :joins value.


Regards,
This topic is locked and can not be replied to.