在我正在构建的应用中,客户选择了一个产品,并且在products/show.html.erb
中,他应该能够在下面的div中看到相关产品。在rails应用中显示随机产品
category.rb和product.rb有关:
cateory.rb has_many :products, :dependent => :nullify
product.rb belongs_to :category belongs_to :label
因此,进出口想做到这一点的最好方式是从同一类别所选产品随机显示产品belongs_to
?
目前,这是我必须在products_controller.rb
@products_rand = Product.offset(offset).limit(6)
我需要它来抓取只产品在同类别作为所选产品的def show
线?
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?
感谢,Postgres的版本的作品。是否有可能从随机产品中排除选定的产品? – Slowboy
您可以使用'where.not。(id:@ product.id)' – Shannon
我从来没有使用'where.not.',它应该来,而不是'where'? – Slowboy