json_api_client icon indicating copy to clipboard operation
json_api_client copied to clipboard

Polymorphic relations

Open babrovka opened this issue 10 years ago • 2 comments

Is there any solutions to have polymorphic relations in the model?

For example:

class Photo belongs_to :article belongs_to :event end

/articles/:id/photos/:id /event/:id/photos/:id

And have such methods for querying photos:

Photo.where(article_id: 1).find(2) Photo.where(event_id: 2).find(3)

Now, two 'belongs_to' relations in the model leads to such method: Photo.where(article_id: 1, event_id: 2).find(2) /articles/:id/event/:id/photos/:id

And if I mention only one relation in the query, it leads to ArgumentError

babrovka avatar Aug 11 '15 10:08 babrovka

I don't have the ability to do polymorphic relations at this time. I will think about it, but if you have suggestions, I'd love to hear them.

chingor13 avatar Aug 14 '15 19:08 chingor13

I think support for polymorphic relationships would be useful, although off the top of my head I'm also not sure how to effectively add support for this.

A temporary work-around would be to have separate models:

class Photo
  def self.table_name
    "photos"
  end
end

# get articles/:article_id/photos/:id
class ArticlePhoto < Photo
  belongs_to :article
end

# get events/:events_id/photos/:id
class EventPhoto < Photo
  belongs_to :event
end

This is can get complicated with many associations, but I think is the best way to implement this for now.

JohnBDonner avatar Sep 06 '17 14:09 JohnBDonner