Created
October 5, 2011 08:01
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | |
| ) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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