Dynamic conditions for relationships in Rails
So we all know that we can add conditions to relationships in Rails to further filter down the returned objects. Sometimes, though, we need them to be a bit more dynamic.
As an example, lets say I have some documents which belong to a job. The documents are created by different users but I want to find all the documents on a job that were created by the user who owns that job.
The Job model has a user_id field because it belongs_to the User model so I can write the relationship to the documents in the Job model like so:
class Job < ActiveRecord::Base
has_many :documents_owned_by_current_user, :class_name => "Document", :conditions => ['created_by_id = #{self.send(:user_id)}']
end
The trick here is to make sure that you use single quotes in the conditions option. We don’t want the string interpolation to be performed when the association is declared, rather we want it to be evaluated at runtime when Rails is busy substituting the conditions into the generated SQL where it inadvertently executes the send method on self.