Skip to content

Instantly share code, notes, and snippets.

@avi-flombaum
Created July 9, 2013 17:57
Show Gist options
  • Save avi-flombaum/5959608 to your computer and use it in GitHub Desktop.
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.
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