Skip to content

Instantly share code, notes, and snippets.

@jasonelston
Created February 21, 2011 23:19
Show Gist options
  • Save jasonelston/837901 to your computer and use it in GitHub Desktop.
Save jasonelston/837901 to your computer and use it in GitHub Desktop.
Problem with using joins with Arel tables and Rails queries
Because of the way I've structure the requests model and it's relationship with ads, I need to be able to do ORs in my query.
Anyway I've found my way to Arel and it looks like it should do the goods for me but I can't get a join working
The existing named scope in the Request class is
scope :responder, lambda { |user| joins(:ad).where(:ads => { :user_id => user }) }
The above works as I expect it to.
According to the doco I can find I should be able to do something like the following to get it working with Arel
requests = Request.arel_table
ads = Ad.arel_table
where(requests.join(ads).on(ads[:id].eq(requests[:ad_id])))
This results in an error
TypeError: Cannot visit Arel::SelectManager
I can do the following in the console though
r = Request.arel_table
a = Ad.arel_table
r.join(a).to_sql
=> "SELECT FROM \"requests\" INNER JOIN \"ads\" "
So it looks like it's forming the SQL request, however when you put that in a where
Request.where(r.join(a)).to_sql
I get the following
TypeError: Cannot visit Arel::SelectManager....
I've tried doing other Arel actions within the where and it works (e.g.)
Request.where(r[:status].eq(nil)).to_sql
=> "SELECT \"requests\".* FROM \"requests\" WHERE (\"requests\".\"status\" IS NULL)"
Any ideas?
@mhuggins
Copy link

I'm encountering the same issue. Have you found a solution?

@jasonelston
Copy link
Author

I can't remember exactly what I was doing :). I believe I actually changed my approach as this was quite an expensive database interaction. I also posted this to stackoverflow which netted some interesting comments. When I get a chance I'll take a look and see if I can find out what I eventually did.

http://stackoverflow.com/questions/5072709/arel-joins-and-rails-queries

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment