LoginSignup
2
0

More than 5 years have passed since last update.

ユーザー登録機能つき投稿サイト➀

Posted at

1,postモデル,コントローラー作成

qiita.rb
1:rails g model post title:string link:string description:text
2:rails db:migrate

3:rails g controller Posts

4:resources :posts
5:root "posts#index"
posts.controller
class PostsController < ApplicationController
    before_action :find_post, only: [:show, :edit, :update, :destroy]

    def index
        @posts = Post.all.order("created_at DESC")
    end

    def show
    end

    def new
        @post = Post.new
    end

    def create
        @post = Post.new(post_params)

        if @post.save
            redirect_to @post
        else
            render "new"
        end
    end

    def edit
    end

    def update
        if @post.update(post_params)
            redirect_to @post
        else
            render "edit"
        end
    end

    def destroy
        @post.destroy
        redirect_to root_path
    end

    private

    def find_post
        #自分のコントローラー内のものを見つける時はparams[:id]、自分のコントローラーに無い時(ex:userコントローラー)はparams[:user_id]で参照
        @post = Post.find(params[:id])
    end

    def post_params
        params.require(:post).permit(:title,:link,:description)
    end
end

index.html.erb
<% @posts.each do |post| %>
<!--postはpost.showへ行く-->
<p><%= post.id %>:<%= link_to post.title,post %></p>
<% end %>

<%= link_to "新規投稿",new_post_path %>
new.html.erb
<h1>post/new</h1>
<%= render "posts/form" %>
show.html.erb
<h1>title:<%= @post.title %></h1>
<h1>link:<%= @post.link %></h1>
<h1>description:<%= @post.description %></h1>
<h1>id:<%= @post.id %></h1>


<%= link_to "編集",edit_post_path(@post) %>
<%= link_to "削除",post_path(@post),method: :delete,data: {confirm:"削除してもいいですか"} %>
<%= link_to "ホーム",root_path %>
edit.html.erb
<h1>編集<h1>
<%= render "posts/form"%>
_form.html.erb
<%= form_for(@post) do |f| %>
   <p>titl:<%= f.text_field :title %></p>
   <p>link:<%= f.text_field :link %></p>
   <p>description:<%= f.text_field :description %></p>
   <p><%= f.button :submit %></p>
<% end %>

12-12/23min

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0