Skip to content

Instantly share code, notes, and snippets.

@schowdhury
Created June 9, 2011 19:07
Show Gist options
  • Save schowdhury/1017462 to your computer and use it in GitHub Desktop.
Save schowdhury/1017462 to your computer and use it in GitHub Desktop.
vanilla ruby class with list of activerecord objects integrates with rails form helpers
#I want to create many of a thing in one shot where thing is an activerecord class with
#validations. I can use the following where a listofthings is a vanilla ruby class. on
#valid? this class calls all the contained object's valid? method. and a naive save that
#calls save on each of the contained activerecord objects. There's some syntatic sugar,
#methods that hide the underlying list. This is minimal code for explanation.
#My thing is an activerecord class
#ListOfMyThings is a vanilla ruby class
#thing to note for form helpers to work you need
# _attributes=(attributes) method defined.
class MyThingValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
value.each do |val|
record.errors[attribute] << val.errors unless val.valid?
end
end
end
class ListOfMyThings
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
#include Enumerable
attr_accessor :my_things
validates :my_things, :my_thing => true
def initialize(my_things = [])
self.my_things = [my_things].flatten
end
#convenience methods
def <<(val)
my_things << val
end
def [](i)
my_things[i]
end
# def each
# my_things.each do |c|
# yield c
# end
# end
def persisted?
false
end
def save
if valid?
my_things.each do |my_thing|
my_thing.save
end
end
end
def my_things_attributes=(attributes)
#logger.warn(attributes.inspect)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment