Created
July 9, 2013 17:57
-
-
Save avi-flombaum/5959608 to your computer and use it in GitHub Desktop.
A form writer to model pattern I use in Rails a lot.
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
class List < ActiveRecord::Base | |
attr_accessible :name, :items_to_add | |
has_many :items | |
# Allows me to easily build forms that do | |
# complex things but still plug into | |
# mass-assignment. | |
def items_to_add=(items) | |
items.each{|i| add_item(i)} | |
end | |
# Don't expose the AR Api outside of the model | |
# or to the form, rather, have an internal API | |
# that form writers can use. | |
def add_item(item) | |
# Also helps people maintain a consistent | |
# way to add association, as opposed to | |
# self.items << Item.new | |
self.items.build(:name => item) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment