I have some confusion regarding how access the join model object that is
responsible for a relationship I am working with. Here’s a simple case:
class A < ActiveRecord::Base
has_many :connections
has_many :bs, :through => :connections
end
class B < ActiveRecord::Base
has_many :connections
has_many :as, :through => :connections
end
class Connection < ActiveRecord::Base
belongs_to :a
belongs_to :b
end
Now say I’ve already got my hands on an A, called a, and one of it’s
b’s. So, I can already say a.bs[b_index].attribute = value. That’s
great. But where is the Connection object that is tying this a to this
particular b? The object must exist. Let’s say I have a reference to it
called c, so that I can say c.attribute = value. But how do I get that
reference?
The only way I can see to do it is to find it manually via it’s own
class’s relationship, as in a.connections.find_by_b_id(b.id). But that
seems very WET (i.e. not DRY) to me; I shouldn’t have to do a search for
an object, that I’m essentially already using.
FWIW, I’ve been searching on this forever, so I apologize if the answer
is out there & I’ve simply failed to find it.
I would have thought I could say a.bs[i].connections and get just an
array of the connection objects that tie b[i] to a. But instead it seems
that I get all of bs[i]'s connections, whether or not they connect b to
a. I would think there would be a simple way to refer to just the
objects that join a specific b to a specific a, without having to
explicitly search for them. Is there?
has_many :connections
great. But where is the Connection object that is tying this a to this
particular b? The object must exist. Let’s say I have a reference to it
called c, so that I can say c.attribute = value. But how do I get that
reference?
The only way I can see to do it is to find it manually via it’s own
class’s relationship, as in a.connections.find_by_b_id(b.id). But that
seems very WET (i.e. not DRY) to me; I shouldn’t have to do a search for
an object, that I’m essentially already using.