Skip to content

Instantly share code, notes, and snippets.

@anndoko anndoko/product.rb
Created Jun 9, 2017

Embed
What would you like to do?
隨機推薦 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
You can’t perform that action at this time.