|
|
|
Tuesday, 05 April 2011 09:32 |
Simplest wrapper for a Rails model, that for view or controlloer behaves like model itself (at least in my app :) ).
class ActiveForm
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
 Read more: |
|
|
Tuesday, 05 April 2011 09:32 |
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
 Read more: |
|
Tuesday, 02 November 2010 10:03 |
# Iterate over one record at a time using ActiveRecord, instead of being slurpy.
def self.foreach(conditions = nil, &block)
conn = connection.raw_connection
sql = "select * from #{table_name}"
sql += " where #{conditions}" if conditions
begin
raw_cursor = conn.exec(sql)
while rec = raw_cursor.fetch_hash
object = self.new
# To get around protected attributes we must assign all attributes
# individually, instead of passing a single hash to self.new.
rec.each{ |key, value|
cname = key.downcase
object.send("#{cname}=", value)
}
yield object
end
ensure
raw_cursor.close if raw_cursor
end
end
 Read more: |
|
|
|
|
|
|