Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

「5. ActiveStorage で画像アップロードを実装する」の差分 / 「6. コメントを付けられるようにする」のスタート地点 #4

Open
wants to merge 14 commits into
base: 05-user_icon
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ gem 'bootsnap', require: false
# gem "sassc-rails"

# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"
gem 'image_processing', '~> 1.2'

group :development, :test do
# See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
Expand Down
1 change: 1 addition & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ DEPENDENCIES
erb_lint
faker
i18n_generators
image_processing (~> 1.2)
importmap-rails
jbuilder
kaminari
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class ApplicationController < ActionController::Base
protected

def configure_permitted_parameters
keys = %i[name postal_code address self_introduction]
keys = %i[name postal_code address self_introduction avatar]
devise_parameter_sanitizer.permit(:sign_up, keys:)
devise_parameter_sanitizer.permit(:account_update, keys:)
end
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/users_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

class UsersController < ApplicationController
def index
@users = User.order(:id).page(params[:page])
@users = User.with_attached_avatar.order(:id).page(params[:page])
end

def show
Expand Down
4 changes: 4 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,8 @@
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable

has_one_attached :avatar do |attachable|
attachable.variant :thumb, resize_to_limit: [150, 150]
end
end
5 changes: 5 additions & 0 deletions app/views/devise/registrations/_profile_fields.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,8 @@
<%= f.label :self_introduction %><br />
<%= f.text_area :self_introduction %>
</div>

<div class="field">
<%= f.label :avatar %><br />
<%= f.file_field :avatar, autocomplete: "avatar" %>
</div>
8 changes: 8 additions & 0 deletions app/views/users/_user.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,12 @@
<%= user.self_introduction %>
</p>

<p>
<strong><%= User.human_attribute_name(:avatar) %>:</strong>
<% if user.avatar.attached? %>
<br>
<%= image_tag user.avatar.variant(:thumb) %>
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

一覧画面でN+1問題が発生しないように改善してみてください。

<% end %>
</p>

</div>
1 change: 1 addition & 0 deletions config/locales/translation_ja.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@ ja:
postal_code: 郵便番号
address: 住所
self_introduction: 自己紹介文
avatar: ユーザ画像
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[5.2]
def change
# Use Active Record's configured type for primary and foreign keys
primary_key_type, foreign_key_type = primary_and_foreign_key_types

create_table :active_storage_blobs, id: primary_key_type do |t|
t.string :key, null: false
t.string :filename, null: false
t.string :content_type
t.text :metadata
t.string :service_name, null: false
t.bigint :byte_size, null: false
t.string :checksum

if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end

t.index [ :key ], unique: true
end

create_table :active_storage_attachments, id: primary_key_type do |t|
t.string :name, null: false
t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type
t.references :blob, null: false, type: foreign_key_type

if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end

t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end

create_table :active_storage_variant_records, id: primary_key_type do |t|
t.belongs_to :blob, null: false, index: false, type: foreign_key_type
t.string :variation_digest, null: false

t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end

private
def primary_and_foreign_key_types
config = Rails.configuration.generators
setting = config.options[config.orm][:primary_key_type]
primary_key_type = setting || :primary_key
foreign_key_type = setting || :bigint
[primary_key_type, foreign_key_type]
end
end
32 changes: 31 additions & 1 deletion db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

91 changes: 55 additions & 36 deletions db/seeds.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# frozen_string_literal: true

# queue_adapterを変更している理由とtransactionを使っている理由は下記URLを参照
# https://bootcamp.fjord.jp/questions/779#answer_2262
ActiveStorage::AnalyzeJob.queue_adapter = :inline

print '開発環境のデータをすべて削除して初期データを投入します。よろしいですか?[Y/n]: ' # rubocop:disable Rails/Output
unless $stdin.gets.chomp.casecmp('Y').zero?
puts '中止しました。' # rubocop:disable Rails/Output
Expand All @@ -10,50 +14,65 @@ def picture_file(name)
File.open(Rails.root.join("db/seeds/#{name}"))
end

puts '実行中です。しばらくお待ちください...' # rubocop:disable Rails/Output

Book.destroy_all

Book.create!(
title: 'Ruby超入門',
memo: 'Rubyの文法の基本をやさしくていねいに解説しています。',
author: '五十嵐 邦明',
picture: picture_file('cho-nyumon.jpg')
)

Book.create!(
title: 'チェリー本',
memo: 'プログラミング経験者のためのRuby入門書です。',
author: '伊藤 淳一',
picture: picture_file('cherry-book.jpg')
)

Book.create!(
title: '楽々ERDレッスン',
memo: '実在する帳票から本当に使えるテーブル設計を導く画期的な本!',
author: '羽生 章洋',
picture: picture_file('erd.jpg')
)

50.times do
Book.transaction do # rubocop:disable Metrics/BlockLength
Book.create!(
title: Faker::Book.title,
memo: Faker::Book.genre,
author: Faker::Book.author,
picture: picture_file('no-image.png')
title: 'Ruby超入門',
memo: 'Rubyの文法の基本をやさしくていねいに解説しています。',
author: '五十嵐 邦明',
picture: picture_file('cho-nyumon.jpg')
)

Book.create!(
title: 'チェリー本',
memo: 'プログラミング経験者のためのRuby入門書です。',
author: '伊藤 淳一',
picture: picture_file('cherry-book.jpg')
)

Book.create!(
title: '楽々ERDレッスン',
memo: '実在する帳票から本当に使えるテーブル設計を導く画期的な本!',
author: '羽生 章洋',
picture: picture_file('erd.jpg')
)

50.times do
Book.create!(
title: Faker::Book.title,
memo: Faker::Book.genre,
author: Faker::Book.author,
picture: picture_file('no-image.png')
)
end
end

User.destroy_all

50.times do |n|
name = Faker::Name.name
User.create!(
email: "sample-#{n}@example.com",
password: 'password',
name:,
postal_code: "123-#{n.to_s.rjust(4, '0')}",
address: Faker::Address.full_address,
self_introduction: "こんにちは、#{name}です。"
)
User.transaction do
50.times do |n|
name = Faker::Name.name
User.create!(
email: "sample-#{n}@example.com",
password: 'password',
name:,
postal_code: "123-#{n.to_s.rjust(4, '0')}",
address: Faker::Address.full_address,
self_introduction: "こんにちは、#{name}です。"
)
end
end

# 画像は読み込みに時間がかかるので一部のデータだけにする
User.order(:id).each.with_index(1) do |user, n|
next unless (n % 8).zero?

number = rand(1..6)
image_path = Rails.root.join("db/seeds/avatar-#{number}.png")
user.avatar.attach(io: File.open(image_path), filename: 'avatar.png')
end

puts '初期データの投入が完了しました。' # rubocop:disable Rails/Output
Binary file added db/seeds/avatar-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added db/seeds/avatar-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added db/seeds/avatar-3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added db/seeds/avatar-4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added db/seeds/avatar-5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added db/seeds/avatar-6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.