Mark Gandolfo's Blog
Associated With is a simple ruby on rails plugin that will check if an object is associated with another object.
has_one and belongs_to
class Computer < ActiveRecord::Base
belongs_to :programmer
end
class Programmer < ActiveRecord::Base
has_one :computer
end
So if, Programmer with id 1, is associated with Computer 1, but not Computer 2 using associated_with? we will return
programmer = Programmer.find(1)
computer = Computer.find(1)
computer2 = Computer.find(2)
programmer.associated_with?(computer)
# => true
programmer.associated_with?(computer2)
# => false
We can even do it the other way around
computer.associated_with?(programmer)
# => true
This will work with all associations with ActiveRecord, for example, a has_many :through
class Analyst < ActiveRecord::Base
has_many :document_stores
has_many :documents, :through => :document_stores
end
class Document < ActiveRecord::Base
has_many :document_stores
has_many :analysts, :through => :document_stores
end
class DocumentStore < ActiveRecord::Base
belongs_to :document
belongs_to :analyst
end
so if document 1 is associated to analyst 1 & 2, but not 3. then
Analyst.find(1).associated_with(Document.find(1))
# => true
Analyst.find(3).associated_with(Document.find(1))
# => false
Check out the tests for more information.