Last active
May 9, 2016 16:16
-
-
Save alexshagov/aff5e2d8764d9fee3ec75c85d01ffcc2 to your computer and use it in GitHub Desktop.
blog 2-4
This file contains hidden or 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 | |
include ActiveModel::Model | |
#Post attributes | |
attribute :post, Object | |
attribute :title, String | |
attribute :body, String | |
#Tag attributes | |
attribute :tags, String # first tag,second tag,third tag | |
#Validations | |
validates :title, :body, presence: true | |
def initialize(attributes = {}) | |
unless attributes[:id].nil? | |
@post = Post.find(attributes[:id]) | |
@id = @post.id | |
@title = attributes[:title].nil? ? @post.title : attributes[:title] | |
@body = attributes[:body].nil? ? @post.body : attributes[:body] | |
@tags = attributes[:tags].nil? ? @post.tags.map(&:title).join(',') : attributes[:tags] | |
else | |
super(attributes) | |
end | |
end | |
def save | |
if valid? | |
persist! | |
else | |
false | |
end | |
end | |
def update | |
if valid? | |
update! | |
else | |
false | |
end | |
end | |
private | |
def persist! | |
@post = Post.create(title: title, body: body) | |
save_tags @post | |
end | |
def update! | |
@post.update_attributes(title: title, body: body) | |
@post.tags.clear | |
save_tags @post | |
end | |
def save_tags post | |
tags.split(',').each { |title| post.tags << Tag.find_or_create_by(title: title) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment