1
2

More than 3 years have passed since last update.

【Ruby on Rails】 refile導入から新規投稿まで

Last updated at Posted at 2020-12-10

目標

rifileを導入、新規投稿まで

開発環境

ruby '2.6.5'
rails '6.0.0'

実装

今回は、投稿機能(post)を例として作成します。

device導入後を前提としています。

Gemに記述

Gemfile
gem "refile", require: "refile/rails", github: 'manfe/refile'
gem "refile-mini_magick"

その後に% bundle install

postモデルを作成

ターミナル
% rails g model post

テーブル作成

model/image_idを持ったモデルを作成

create_posts.rb

class CreatePosts < ActiveRecord::Migration[6.0]
  def change
    create_table :posts do |t|
      t.text        :title,           null: false
      t.string      :post_image_id,  null: false
      t.references  :user,           foreign_key: true
      t.timestamps
    end
  end
end

その後に% rails db:migrate

modelの編集

app/models/post.rb

class Post < ApplicationRecord

  belongs_to :user

  attachment :post_image # ここを追加(_idは含めない)

end

posts.controllerを作成

ターミナル
% rails g controller posts

controllerの編集

app/controllers/posts_controller.rb

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to root_path
    else
      render :new
    end
  end

  private
  def post_params
    params.require(:post).permit(:title, :post_image).merge(user_id: current_user.id)
  end
end

 :post_imageに_idを記述しない

ルーティングを編集

routes.rb
Rails.application.routes.draw do
  devise_for :users
  root to: 'posts#index'
  resources :posts
end

投稿をページを作成

app/views/posts/new.html.erb
 <div>
   <%= form_with(model: @post, url: posts_path, local: true) do |f| %>
     <%= f.attachment_field :post_image %>
     <%= f.text_area :title %>
     <%= f.submit "投稿を送信" %>
   <% end %>
 </div>

 file_fieldではなく、attachment_fieldでファイルを選択させる
 ここでも_idは付けない

クラスを付けたい場合

<%= f.attachment_field :post_image, class: :"クラス名" %>

後編【refileを使用した投稿一覧ページの作成】

1
2
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
1
2