DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Alexey has posted 28 posts at DZone. View Full User Profile

FormModel

04.05.2011
| 3882 views |
  • submit to reddit
        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