FormModel
Join the DZone community and get the full member experience.
Join For FreeSimplest wrapper for a Rails model, that for view or controlloer behaves like model itself (at least in my app :) ).
class FormModel
extend Forwardable
def attributes= attributes
@attributes = attributes
end
def initialize object
@object = object
end
def save
@object.attributes = @attributes
@object.save
end
def self.attr_delegators *attrs
def_delegators :@object, *attrs
end
def_delegators :@object, :errors, :to_key, :to_param, :persisted?
cattr_accessor :model_class
def self.model_name
@@model_class.model_name
end
end
Example form:
class EntryForm < ActiveForm
self.model_class = Entry
attr_delegators :text, :title, :add_to
end
In controller:
def update
@entry = EntryForm.new Entry.find(params[:id])
@entry.attributes = params[:entry]
if @entry.save
redirect_to @entry
else
render :edit
end
end
Opinions expressed by DZone contributors are their own.
Comments