Ruby on Railsを用いた簡単なブログサービスの作り方

はい、rails g controllerを使ってコントローラーを生成し、手動で必要なアクションを追加する方法が一般的です。それでは、rails g controllerを使用した手順を詳しく説明します。

1. 新しいRailsプロジェクトを作成

まず、Railsプロジェクトを作成します。

rails new blog_app --database=postgresql
cd blog_app

2. Gemfileに必要なGemを追加

GemfileにShrineとImage Processingライブラリを追加します。

gem 'shrine'
gem 'image_processing', '~> 1.2'

次に、Bundleインストールを実行します。

bundle install

3. Shrineのセットアップ

次に、Shrineの設定ファイルを作成します。config/initializers/shrine.rbを作成して、以下のコードを追加します。

require "shrine"
require "shrine/storage/file_system"

Shrine.storages = {
  cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"), # 一時保存
  store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store"), # 永続保存
}

Shrine.plugin :activerecord
Shrine.plugin :cached_attachment_data # フォーム再表示時にキャッシュされたファイルを保持
Shrine.plugin :restore_cached_data    # キャッシュされたファイルのメタデータを再取得

4. Postモデルの作成

次に、ブログのタイトル、本文、画像データを管理するためのPostモデルを作成します。

rails generate model Post title:string body:text image_data:text
rails db:create
rails db:migrate

app/models/post.rbを編集して、Shrineを統合します。

class Post < ApplicationRecord
  include ImageUploader::Attachment(:image) # Shrineアップローダーを統合
end

5. ImageUploaderの作成

次に、app/uploaders/image_uploader.rbを作成し、以下のコードを追加します。

class ImageUploader < Shrine
  # Shrineに必要な設定をここに追加できます
end

6. Postsコントローラーの作成

rails g controllerコマンドを使用して、PostsControllerを生成します。

rails g controller Posts

生成されたapp/controllers/posts_controller.rbを編集して、以下のコードを追加します。

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  def index
    @posts = Post.all
  end

  def show
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to @post, notice: 'Post was successfully created.'
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @post.update(post_params)
      redirect_to @post, notice: 'Post was successfully updated.'
    else
      render :edit
    end
  end

  def destroy
    @post.destroy
    redirect_to posts_url, notice: 'Post was successfully destroyed.'
  end

  private

  def set_post
    @post = Post.find(params[:id])
  end

  def post_params
    params.require(:post).permit(:title, :body, :image)
  end
end

7. ルーティングの設定

config/routes.rbpostsリソースを設定します。

Rails.application.routes.draw do
  resources :posts
  root "posts#index"
end

8. ビューの作成

次に、ビューを作成します。app/views/posts/ディレクトリ内に以下のファイルを作成します。

1. index.html.erb

<h1>Posts</h1>

<%= link_to 'New Post', new_post_path %>

<ul>
  <% @posts.each do |post| %>
    <li>
      <%= link_to post.title, post %>
    </li>
  <% end %>
</ul>

2. show.html.erb

<h1><%= @post.title %></h1>
<p><%= @post.body %></p>

<% if @post.image %>
  <%= image_tag @post.image.url %>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

3. new.html.erb & edit.html.erb

これらは同じフォームを使用します。まず、_form.html.erbを作成します。

<%= form_with(model: @post, local: true) do |form| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
        <% @post.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :body %>
    <%= form.text_area :body %>
  </div>

  <div class="field">
    <%= form.label :image %>
    <%= form.file_field :image %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

new.html.erbedit.html.erbでこのフォームを呼び出します。

<h1>New Post</h1>
<%= render 'form', post: @post %>
<%= link_to 'Back', posts_path %>
<h1>Edit Post</h1>
<%= render 'form', post: @post %>
<%= link_to 'Back', posts_path %>

9. サーバーの起動と確認

最後にサーバーを起動して、ブラウザでアプリケーションの動作を確認します。

rails server

http://localhost:3000/postsにアクセスし、ブログ投稿と画像アップロードが動作することを確認します。


これでrails g controllerを使用した、Shrineを活用した画像アップロード機能付きブログ投稿サービスが完成です。

コメント

タイトルとURLをコピーしました