What's the best way to make 1 SQL call that checks if the join model already exists before we try to create another with this setup:
class Parent < ActiveRecord::Base
has_many :relationships, :as => :parent
has_many :children, :through => :relationships, :class_name => "Child"
end
class Child < ActiveRecord::Base
has_many :relationships, :as => :child
has_many :parents, :through => :relationships, :class_name => "Parent"
end
class Relationship < ActiveRecord::Base
belongs_to :parent, :polymorphic => true
belongs_to :child, :polymorphic => true
# this is the bottleneck, requires making 4 sql calls!
validates_presence_of :parent_id, :scope => [:child_id, :parent_type]
validates_presence_of :child_id, :scope => [:parent_id, :child_type]
end
When I do this:
parent = Parent.create!
child = Child.create!
parent.children << child
parent.children << child
...the second time around the validation runs and it makes a bunch of sql calls. What's a good way to write this to make it only require 1 SQL command?