Skip to content

Instantly share code, notes, and snippets.

@sinsoku
Last active March 18, 2016 14:48
Show Gist options
  • Save sinsoku/a0f1e00c3b8f77898333 to your computer and use it in GitHub Desktop.
Save sinsoku/a0f1e00c3b8f77898333 to your computer and use it in GitHub Desktop.
action resource
# app/models/posts/action.rb
class Action
include ActiveModel::Model
attr_reader :post_id, :name
def save
return false if invalid?
@post = Post.find(post_id)
if name == 'publish'
@post.update state: :publish, published_at: Time.zone.now
elsif name == 'xxx'
# do something
end
# 適当にif分岐にしてるけど、本当はもう少しクラス設計を直して、if文がなくなるようにした方が良い
end
end
# app/controllers/posts/actions_controller.rb
module Posts
class ActionsController < ApplicationController
# POST /posts/:post_id/actions.json
def create
@action = Posts::Action.new(post_id: params[:post_id], name: params[:name])
respond_to do |format|
if @action.save
format.json { render json: @action, status: :created }
else
format.json { render json: @action.errors, status: :unprocessable_entity }
else
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment