前提・実現したいこと
ajaxを使用してモーダル発火時にランダムに商品情報を表示させたい。
attrを使ってurlを結合させてたいのですが、refileを使用して登録された画像のurlの取得方法がわからないです。
該当のソースコード
ruby
1<div id="overlay"> 2 <div id="result"> 3 <h2>discover new music</h2> 4 <div id="content-title"><a href=""></a></div> 5 <div id="content-image"><img src=""></div> 6 <%#= link_to @random_product.product_title, @random_product, id: "content-title" %> 7 <%#= attachment_image_tag @random_product, :image, :fill, 300, 300, format: 'jpeg', id: 'content-image', fallback: 'img/no_image.png', size: '300x300' %> 8 <button id="close">X</button> 9 </div> 10</div>
js
1<script> 2 $(function(){ 3 $(document).on('click', '#rock,#pop,#punk', function(){ 4 $.ajax({ 5 type:'GET', 6 url:'/api/json_top', 7 dataType: 'json', 8 }) 9 .done(function(data){ 10 console.log(data.id); 11 console.log(data.image); 12 $('#content-title,#content-image').empty(); 13 $('#overlay,#result').fadeIn(); 14 $('#content-title a').attr('href', '/products/' + 'data.id'); 15 $('#content-image img').attr('src', 'data.image'); 16 $(document).on('click', '#overlay,#close', function(){ 17 $('#overlay,#result').fadeOut(); 18 $(document).on('click', '#result', function(e){ 19 e.stopPropagation(); 20 }); 21 }); 22 }) 23 24 .fail(function(){ 25 alert('fail') 26 }); 27 }); 28 });
class Api::RootsController < ApplicationController def top @random_product = Product.order("RANDOM()").first render :json => { id: @random_product.id, image: @random_product.image_id } end end
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。