LoginSignup
0
0

More than 1 year has passed since last update.

複数枚画像のスライド機能実装(carrierwaveとswiper使用)

Last updated at Posted at 2022-08-11

スライド機能実装する時に参考になるサイトはこちらです。

❶carrierwaveとswiperに関してはこちらから参照下さい。

とてもわかりやすくまとまってます!

❷完成イメージはこちらのサイトで確認できます。

アレンジを加えれるので、オススメです!

❶の記事を見ながら『carrierwaveとswiper』を適用させた状態でざっくりと自分で適用できた記述を紹介します。
1.dbにカラム追記
postに
 create_table "posts", force: :cascade do |t|
    t.integer "user_id", null: false
    t.string "title", null: false
    ~~~{省略}~~~
    t.json "images"
end
2.投稿フォームのあるmodelに追記
post.rb
mount_uploaders :images, ImageUploader
3.controllerのparamsに追記
posts.controller.rb
def post_params
    params.require(:post).permit(:title,~{省略}~, images: [])
end
4.layout/application.html.erbに追記
application.html.erb
<head>
<!--swiperを読み込ませる-->
    <script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
</head>
5.投稿フォームに追記
new.html.erb
<%= f.file_field :images, accept: "image/*", id: "image", multiple: true, class: "form-control-file image" %>
6.表示させたいviewに追記
スライド表示させたい.html.erb
<div class="swiper mySwiper">
  <div class="swiper-wrapper">
    <% @post.images.each do |image| %>
    <div class="swiper-slide" role="group">
      <%= image_tag image.url, size:'100x100' %>
    </div>
    <% end %>
  </div>
  <div class="swiper-button-next"></div>
  <div class="swiper-button-prev"></div>
  <div class="swiper-pagination"></div>
</div>

~~省略~~

<script>
  var swiper = new Swiper(".mySwiper", {
    
    navigation: {
      nextEl: ".swiper-button-next",
      prevEl: ".swiper-button-prev",
    },
    pagination: {
    el: ".swiper-pagination"
    },
  });
</script>

※本当はjsファイルに読み込ませたいが、よくわからなかったので、viewにscriptタグで適用させてしまいました。
※scriptタグ内で多彩なアレンジが可能(❷の記事を参照)

おまけ

表示させたいviewに追記
1枚だけ表示させたいページ.html.erb
<%= image_tag post.images[0].to_s, size: '100x100' %>
<!--images[0] => 表示させたい順番の番号を記載-->

初学者ですので、間違いがありましたら申し訳ございません。
色んな記事と見て難しい印象でしたが、シンプルな記述でわかりやすかったです!

0
0
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
0
0