|
| 1 | +class PostsController < ApplicationController |
| 2 | + before_action :set_post, only: %i[ show edit update destroy ] |
| 3 | + |
| 4 | + # GET /posts or /posts.json |
| 5 | + def index |
| 6 | + @posts = Post.all |
| 7 | + end |
| 8 | + |
| 9 | + # GET /posts/1 or /posts/1.json |
| 10 | + def show |
| 11 | + end |
| 12 | + |
| 13 | + # GET /posts/new |
| 14 | + def new |
| 15 | + @post = Post.new |
| 16 | + end |
| 17 | + |
| 18 | + # GET /posts/1/edit |
| 19 | + def edit |
| 20 | + end |
| 21 | + |
| 22 | + # POST /posts or /posts.json |
| 23 | + def create |
| 24 | + @post = Post.new(post_params) |
| 25 | + |
| 26 | + respond_to do |format| |
| 27 | + if @post.save |
| 28 | + format.html { redirect_to @post, notice: "Post was successfully created." } |
| 29 | + format.json { render :show, status: :created, location: @post } |
| 30 | + else |
| 31 | + format.html { render :new, status: :unprocessable_entity } |
| 32 | + format.json { render json: @post.errors, status: :unprocessable_entity } |
| 33 | + end |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + # PATCH/PUT /posts/1 or /posts/1.json |
| 38 | + def update |
| 39 | + respond_to do |format| |
| 40 | + if @post.update(post_params) |
| 41 | + format.html { redirect_to @post, notice: "Post was successfully updated." } |
| 42 | + format.json { render :show, status: :ok, location: @post } |
| 43 | + else |
| 44 | + format.html { render :edit, status: :unprocessable_entity } |
| 45 | + format.json { render json: @post.errors, status: :unprocessable_entity } |
| 46 | + end |
| 47 | + end |
| 48 | + end |
| 49 | + |
| 50 | + # DELETE /posts/1 or /posts/1.json |
| 51 | + def destroy |
| 52 | + @post.destroy! |
| 53 | + |
| 54 | + respond_to do |format| |
| 55 | + format.html { redirect_to posts_path, status: :see_other, notice: "Post was successfully destroyed." } |
| 56 | + format.json { head :no_content } |
| 57 | + end |
| 58 | + end |
| 59 | + |
| 60 | + private |
| 61 | + # Use callbacks to share common setup or constraints between actions. |
| 62 | + def set_post |
| 63 | + @post = Post.find(params.expect(:id)) |
| 64 | + end |
| 65 | + |
| 66 | + # Only allow a list of trusted parameters through. |
| 67 | + def post_params |
| 68 | + params.expect(post: [ :content ]) |
| 69 | + end |
| 70 | +end |
0 commit comments