DEV Community

Augusts Bautra
Augusts Bautra

Posted on

How to split out a specific case from a polymorphic association

Let's say we have a model structure that allows us to make comments on anything:

Comment.has_one :comment_commentee_tie

CommentCommenteeTie
  belongs_to :comment
  belongs_to :commentee, polymorphic: true

Post
  has_many :comment_commentee_ties
Enter fullscreen mode Exit fullscreen mode

Now let's say we want to filter comments by possible post data. To alleviate the joining, we can define a non-polymorphic association for Comment:

Comment
  has_one :comment_commentee_tie
  has_one :post, through: :comment_commentee_tie, source: :commentee, source_type: "Post"
Enter fullscreen mode Exit fullscreen mode

Polymorphic children

Let's look at the harder case with has_many :children, polymorphic: true

We can use the scope option to filter what types of children we want:

Parent
  has_many :parent_child_ties

  has_many(
    :good_children,
    -> { where(child_type: "GoodChild") },
    through: :parent_child_ties,
    source: :child,
    source_type: "GoodChild"
  )
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay