Skip to content

Instantly share code, notes, and snippets.

@anndoko
Created June 9, 2017 13:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anndoko/bc181338f5ae3afc202db93f4ddb21ab to your computer and use it in GitHub Desktop.
Save anndoko/bc181338f5ae3afc202db93f4ddb21ab to your computer and use it in GitHub Desktop.
隨機推薦 3 樣商品
# app/models/product.rb
# scope,隨機選 3 項商品
scope :random3, -> { limit(3).order('RANDOM()') }
# app/controllers/products_controller.rb
def show
@product = Product.find(params[:id])
# 隨機推薦 3 項商品
@suggests = Product.random3
end
# app/views/products/show.html.erb
<!-- 隨機推薦商品,將 @suggests 印出來 -->
<% @suggests.each_with_index do |product, index| %>
<div class='col-xs-12 col-sm-4 col-md-4 suggested-product-content'>
<!-- 連結,在迴圈裡的內容(圖片)會連至 product_path(product) -->
<%= link_to product_path(product) do %>
<!-- 商品圖片 -->
<% if product.product_images.present? %>
<!-- 顯示第一張圖片 -->
<%= image_tag(product.product_images[0].image.other.url, class: 'thumbnail')%>
<% else %>
<%= image_tag('http://placehold.it/100x100&text=No Pic', class: 'thumbnail') %>
<% end %>
<% end %>
</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment