LoginSignup
70
67

More than 3 years have passed since last update.

【Rails】画像のパスを指定する

Last updated at Posted at 2019-12-09

Railsアプリを作成中、画像パスの指定でつまづいたのでメモ

前提

sass-railsを使っている。(デフォルトで入っていた)
画像はapp/assets/images/orpublic/に保存。

HTMLから指定

htmlのimgタグを使って、<img src='assets/{ファイル名}'>のような指定もできますが、何かと不具合が起きやすいのでimage_tagを使うようにしましょう。

app/assets/image/以下の画像

<%= image_tag '<ファイル名>'で指定。

<%= image_tag 'logo.png' %>

またはsrc="/assets/<ファイル名>"で指定

<img src="/assets/logo.png" alt="">

public/以下の画像

<%= image_tag '<publicディレクトリからの相対パス>'で指定

<%= image_tag '/logo.png' %>

Sassファイルから指定

app/assets/image/以下の画像

image-url('<ファイル名>')で指定

app/assets/stylesheets/style.scss
h1 {
  background-image: image-url('logo.jpg')
}

public/以下の画像

app/assets/stylesheets/style.scss
h1 {
  background-image: url("/images/hogehoge.png");
}

その他

開発者が用意するファイルはapp/assets/images/に保存して、public/にはユーザーがアップロードした画像とかを保存する、といった使い分けが一般的なようです。

参考

Rails で背景に画像を表示したいのですが取り込み方を教えてください。
Railsで扱う画像はassetsとpublic、どちらに置くといいのでしょうか?

70
67
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
70
67