Finding rows not connected through :though

I have a many-to-many relation that uses an intermediate join model and
the :through option of has_many, like this
ModelA
has_many ModelAB
has_many ModelB :through ModelAB

ModelB
has_many ModelAB
has_many ModelA :through ModelAB

ModelAB
belongs_to ModelA
belongs_to ModelB

Now it is easy to find all ModelB objects that are connected to some
ModelA object. But what is the best way to find all ModelB objects that
are NOT connected to some specific ModelA object?
What is the usual pattern to let the user add new ModelA objects to some
ModelB object? I am considering to show a list of objects that are not
yet added and let them select the ones to be added via some checkbox.

So how can I find the set of ModelA objects not connected to the current
ModelB object (or vice versa)?

For example, you can use find_by_sql method (if you have a
corresponding tables model_a, model_b, model_ab):

a_without_b = ModelA.find_by_sql “SELECT model_a.* FROM model_a,
model_ab WHERE model_a.id = model_ab.model_a_id AND model_ab.model_b_id
= NULL”

Best Regards, Sergey

If you like to study more about this topic then I recommend to read:
http://blog.hasmanythrough.com/articles/category/associations

It helps a lot.

Priit

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs