Skip to content

Instantly share code, notes, and snippets.

@drogus
Last active Aug 29, 2015
Embed
What would you like to do?
form objects
class PostForm
include Virtus.model
extend ActiveModel::Naming
include ActiveModel::Validations
attribute :id, Integer
attribute :title, String
attribute :body, String
validates :title, presence: true
def persisted?
id.present?
end
def self.model_name
@_model_name ||= ActiveModel::Name.new(self, nil, "Post")
end
def initialize(attributes, id = nil)
super(attributes)
self.id = id if id # force id from params[:id] if present
end
def save
if valid?
# save all the things here
end
end
def fetch_post
persisted? ? Post.find(id) : Post.new
end
end
class PostsController
def edit
@post = PostForm.new(post.attributes, post.id)
end
def update
@post = PostForm.new(params[:post], params[:id])
if @post.save
redirect_to @post
else
render :edit
end
end
private
def post
Post.find(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment