Rails 5: Using find_or_create_by for nested attributes

Dana Scheider
Sep 4, 2018 · 1 min read

We had a little bit of a challenge at InView today: how to use nested attributes in forms without necessarily creating a new record in the database for every form submission. The solution turned out to be quite simple.

At InView, we have two (relevant) models: Report and Category. A Report has_and_belongs_to_many Categories. Each Category has one attribute: name. Category names should be unique (although this isn’t enforced through ActiveRecord for reasons I won’t go into here). For this reason, when a report is submitted with nested attributes for its categories, the categories should not be created anew if there is an existing category with the same name. Instead, the existing category should be assigned to the report.

The solution to this ended up being a simple before_save hook in the Report model:

There you go! Now the app first checks if the category is already in the database before creating a new one.

InView Technical Blog

Blog discussing technical issues encountered by the InView project.

Dana Scheider

Written by

Technical lead at InView Dating (https://inview.info)

InView Technical Blog

Blog discussing technical issues encountered by the InView project.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade