add post
This commit is contained in:
53
app/controllers/posts_controller.rb
Normal file
53
app/controllers/posts_controller.rb
Normal file
@@ -0,0 +1,53 @@
|
||||
class PostsController < ApplicationController
|
||||
before_action :set_post, only: %i[ show update destroy ]
|
||||
|
||||
# GET /posts
|
||||
# GET /posts.json
|
||||
def index
|
||||
@posts = Post.all
|
||||
end
|
||||
|
||||
# GET /posts/1
|
||||
# GET /posts/1.json
|
||||
def show
|
||||
end
|
||||
|
||||
# POST /posts
|
||||
# POST /posts.json
|
||||
def create
|
||||
@post = Post.new(post_params)
|
||||
|
||||
if @post.save
|
||||
render :show, status: :created, location: @post
|
||||
else
|
||||
render json: @post.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
# PATCH/PUT /posts/1
|
||||
# PATCH/PUT /posts/1.json
|
||||
def update
|
||||
if @post.update(post_params)
|
||||
render :show, status: :ok, location: @post
|
||||
else
|
||||
render json: @post.errors, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
# DELETE /posts/1
|
||||
# DELETE /posts/1.json
|
||||
def destroy
|
||||
@post.destroy
|
||||
end
|
||||
|
||||
private
|
||||
# Use callbacks to share common setup or constraints between actions.
|
||||
def set_post
|
||||
@post = Post.find(params[:id])
|
||||
end
|
||||
|
||||
# Only allow a list of trusted parameters through.
|
||||
def post_params
|
||||
params.require(:post).permit(:content, :user_id, :quoted_post_id)
|
||||
end
|
||||
end
|
||||
27
app/models/post.rb
Normal file
27
app/models/post.rb
Normal file
@@ -0,0 +1,27 @@
|
||||
class Post < ApplicationRecord
|
||||
belongs_to :user
|
||||
belongs_to :quoted_post, optional: true, class_name: 'Post'
|
||||
|
||||
validates :content, length: { maximum: 777 }
|
||||
validates :content, presence: true, if: :quoted_post?
|
||||
|
||||
def kind
|
||||
if quoted_post?
|
||||
:quoted_post
|
||||
elsif repost?
|
||||
:repost
|
||||
else
|
||||
:post
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def quoted_post?
|
||||
content.present? && quoted_post_id
|
||||
end
|
||||
|
||||
def repost?
|
||||
content.blank? && quoted_post_id
|
||||
end
|
||||
end
|
||||
4
app/views/posts/_post.json.jbuilder
Normal file
4
app/views/posts/_post.json.jbuilder
Normal file
@@ -0,0 +1,4 @@
|
||||
json.extract! post, :id, :content, :user_id, :created_at, :updated_at
|
||||
json.url post_url(post, format: :json)
|
||||
|
||||
json.quoted_post(post.quoted_post)
|
||||
1
app/views/posts/index.json.jbuilder
Normal file
1
app/views/posts/index.json.jbuilder
Normal file
@@ -0,0 +1 @@
|
||||
json.array! @posts, partial: "posts/post", as: :post
|
||||
1
app/views/posts/show.json.jbuilder
Normal file
1
app/views/posts/show.json.jbuilder
Normal file
@@ -0,0 +1 @@
|
||||
json.partial! "posts/post", post: @post
|
||||
Reference in New Issue
Block a user