relationships question

Hi,

I have the following type of situation: three different models (X, Y,
Z). There is no relationship between X and Y, but Y should have_many
of Z (although I'm not convinced Z should belong_to Y, and it may even
belong_to both Y and X). Instances of Z are created for specific
combinations of X and Y (ie, Z will likely have the fields x_id and
y_id). Z will also contain a name that will be used as an identifier
for an instance Y to an instance of X.

I'm not sure if I should simply have a has_many/belongs_to
relationship between Y and Z, and then search through this subset for
an instance of X (to identify the instance of Y as Z) or if there is a
more eloquent way to achieve this.

Any thoughts/ideas would be appreciated.

Thanks,

Simon

X: has_many :zs
Y: has_many :zs
Z: belongs_to :y, belongs_to :x

Since you want to specify Zs that correspond to an association between
x and y it sounds like the best solution is to introduce a fourth
model to capture the state of the association and then let it be the
owner of the relationship to Z. The canonical example has been the
publishing house that has Customers and Publications; the Subscription
model is introduced to map the association between Customer and
Publication.

In your scenario, it sounds like the following might work:

class X
  has_many :xys
  has_many :zs, :through=>:xys
end

class Y
  has_many :xys
  has_many :zs, :through=>:xys
end

class Z
  belongs_to :xy
end

class XY
  belongs_to :x
  belongs_to :y
end

By doing this X and Y have a view into their relationship to one
another and both can see the Zs they know about.