crashtech/torque-postgresql

polymorphic belongs_to_many?

Closed this issue · 5 comments

I wonder why current implementation of belongs_to_many cannot be polymorphic. Is there some restriction inside AR or is it just a lack of time to add support for it?

Hi @LinchSmyth. The thing with polymorphic belongs_to_many is that since it relies on 2 columns, it would be confusing the mapping of 2 disconnected array columns. In such a case, I would recommend you to use a join table which seems more appropriate.

mapping of 2 disconnected array columns

sorry, what is second one array column? In my case I would like to have regular xxx_type column, so instead of xxx_id it will just have xxx_ids.

I don't think that it would be wise to have 2 connected arrays to manage array-basedhas_many polymorphic associations. If you need that, you can always use an intermediate table and use the has_and_belong_to_many type of association that does support polymorphic.

I think you didn't understand: not 2 connected arrays, just one. I don't need polymorphic resource to belong to many different reources, just to many resources of the same model. Not this:

imageable_ids: [1, 2]
imageable_types: ['Post', 'User']

but this:

imageable_ids: [1, 2]
imageable_type: 'Post'

which is how it should work IMO to be compatible with rails default belongs_to.

Or I just can't understand what second array column you are talking about 😕

I consider the first example 2 connected arrays since the information of one is only valid with the information of the second one.

The second example doesn't quite make sense because if they will always belong to the same type, then you can just have imageable_ids: [1, 2] pointing out to the posts table.

The polymorphic behavior means id + type, so the first example would be the correct one, but that adds complications to the whole process. Instead of using arrays, use the has_and_belong_to_many association. You will get the same result with just an intermediate table. The array association was created to avoid the intermediate table in simple situations, that is why I did not add support for polymorphic, because polymorphic is not a simple scenario, so it makes sense to have an intermediate table.