Created
June 9, 2017 13:27
-
-
Save anndoko/bc181338f5ae3afc202db93f4ddb21ab to your computer and use it in GitHub Desktop.
隨機推薦 3 樣商品
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/product.rb | |
# scope,隨機選 3 項商品 | |
scope :random3, -> { limit(3).order('RANDOM()') } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/products_controller.rb | |
def show | |
@product = Product.find(params[:id]) | |
# 隨機推薦 3 項商品 | |
@suggests = Product.random3 | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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