【发布时间】:2017-05-22 01:16:11
【问题描述】:
在我正在构建的应用程序中,客户选择了一种产品,在products/show.html.erb 中,他应该能够在下面的 div 中看到相关产品。
category.rb 和 product.rb 相关:
cateory.rb
has_many :products, :dependent => :nullify
product.rb
belongs_to :category
belongs_to :label
所以我认为最好的方法是显示与所选产品belongs_to相同类别的随机产品?
目前这是我在products_controller.rb 中的def show 行中所拥有的
@products_rand = Product.offset(offset).limit(6)
我需要它来只抓取与所选产品相同类别的产品吗?
products_controller.rb
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def show
offset = rand(100)
@meta_title = "Mypage #{@product.title}"
@meta_description = @product.description
@products_rand = Product.offset(offset).limit(6)
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description, :image, :category_id, :stock_quantity, :label_id, :query, :slug)
end
end
并且随机产品显示在这个views/products/show.html.erb
<div class="row product-teaser">
<h4 class="text-center teaser-text"> Products from same category </h4>
<% @products_rand.each do |product| %>
<div class="col-sm-2 col-xs-3 center-block product-thumbs-product-view" >
<%= link_to product_path (product) do %>
<%= image_tag product.image.url, :size => "100%x100%", class: "img-responsive center-block" %>
<% end %>
<h5 class="text-center"><%= link_to product.title, product, class: "text-center" %></h5>
</div>
<% end %>
</div>
这里是关于这个Not able to display random images below product image in Ruby on rails app?的上一个问题的链接
【问题讨论】:
标签: ruby-on-rails ruby postgresql random many-to-many