Created
August 13, 2009 10:34
-
-
Save mrrooijen/167087 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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