Rails 5: Using find_or_create_by for nested attributes
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.

