Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# Add this snippet into your ApplicationHelper to make it available to all views
# This method enables a simple but clean way to handle nested forms when a :has_many relationship
# along with the :accepts_nested_attributes_for methods are invoked in the model.
# Instead of making a method for each of the first arguments of the form_for() method, you can now just
# invoke the "nestable()" method and pass in the object in the first argument, followed by any associated/nested models.
# See the method and example comments below
module ApplicationHelper
# Call on first argument of the "form_for" method
# form_for(nestable(@user, :phones, :addresses, :computers))
def nestable(object, *nested_models)
returning(object) do |o|
nested_models.each do |nested_model|
o.send(nested_model).build if o.send(nested_model).empty?
# For a practical example:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.