---
# System prepended metadata

title: Rails 圖片（在地）

---

# Rails 圖片（在地）
> https://guides.rubyonrails.org/active_storage_overview.html

## 1.首先把Ｇemfile的 `gem "image_processing", ">= 1.2"`
## 這行註解取消掉。

終端機執行```rails active_storage:install ```

## 2.在`config/environments/development.rb`加上

```ruby
# Store files locally.
config.active_storage.service = :local
```
如果要用s3

```ruby
# Store files on Amazon S3.
config.active_storage.service = :amazon
```
並且在`config/storage.yml`加上
```ruby
local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

amazon:
  service: S3
  access_key_id: ""
  secret_access_key: ""
  bucket: ""
  region: "" # e.g. 'us-east-1'

```

## 3.has_one_attached
在想要加上圖片功能的model加上has_one_attached，這裡用User這個model，:avatar是符號，可以改成其他名字例如:image
```ruby
class User < ApplicationRecord
  has_one_attached :avatar
end

```
如果沒有這個model也可以用終端機增加
```
bin/rails generate model User avatar:attachment
```

在你的form表單上用
```ruby
<%= form.file_field :avatar %>
```

並且在controller上permit :avatar

```ruby
class SignupController < ApplicationController
  def create
    user = User.create!(user_params)
    session[:user_id] = user.id
    redirect_to root_path
  end

  private
    def user_params
      params.require(:user).permit(:email_address, :password, :avatar)
    end
end
```

想要把圖片呈現在view上的話，
```ruby
<%= image_tag user.avatar %>
```

```ruby
<%= image_tag user.avatar.variant(resize_to_limit: [100, 100]) if user.avatar.attached?%>
```
```
if user.avatar.attached?
```
判斷是否有圖片

```
resize_to_limit
```
用來限制其大小