Last active
August 29, 2015 14:03
-
-
Save drogus/2fc6f9eae6fdb36bab71 to your computer and use it in GitHub Desktop.
form objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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