Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

FormModel

DZone's Guide to

FormModel

·
Free Resource
Simplest 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 
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}