Find an article

Start typing to search the archive.

← All articles

Build associations automatically in fields_for helper

Check out my gem. It is an extension for the fields_for helper that lets you avoid boring code for creating associated objects in belongs_to and has_one associations.

Assume you have code in your project like this:

form_for :company do |f|
  f.fields_for(:user, f.object.user || f.object.build_user) do |ff|
    ff.text_field :name

With the get_or_build gem, you can turn this code into the following:

form_for :company do |f|
  f.fields_for(:user, :build_association => true) do |ff|
    ff.text_field :name

I hope you will enjoy this gem! Thank you for your attention!