Skip to content

Instantly share code, notes, and snippets.

@codespore
Created October 5, 2011 08:01
Show Gist options
  • Select an option

  • Save codespore/1263909 to your computer and use it in GitHub Desktop.

Select an option

Save codespore/1263909 to your computer and use it in GitHub Desktop.
Left outer joining 2 fields referring to same User model in Rails 3
t = Task.arel_table
u = User.arel_table
c = u.alias("creators")
keyword = "%#{params}%"
relation = joins("LEFT OUTER JOIN users ON users.id = tasks.user_assigned_id")
.joins("LEFT OUTER JOIN users as #{c.name} ON #{c.name}.id = tasks.creator_id")
.where(
t[:id].matches(keyword)
.or(u[:username].matches(keyword))
.or(c[:username].matches(keyword))
)
@codespore
Copy link
Author

Some background information:

class Task < ActiveRecord::Base
belongs_to :user_assigned, :class_name => "User", :foreign_key => :user_assigned_id
belongs_to :creator, :class_name => "User", :foreign_key => :creator_id
end

Intention:
Wanted to search for username belong to either the user_assigned or creator

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