Skip to content

Instantly share code, notes, and snippets.

@drogus
Last active August 29, 2015 14:03
Show Gist options
  • Save drogus/2fc6f9eae6fdb36bab71 to your computer and use it in GitHub Desktop.
Save drogus/2fc6f9eae6fdb36bab71 to your computer and use it in GitHub Desktop.
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