Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrrooijen/167087 to your computer and use it in GitHub Desktop.
Save mrrooijen/167087 to your computer and use it in GitHub Desktop.
# 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?
end
end
end
end
# For a practical example: http://therailworld.com/posts/20-Nested-Object-Forms-in-Rails-2-3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment