显示具有不同计数轨道的类似项目5.1

时间:2018-03-09 18:30:12

标签: ruby-on-rails

我试图在我的节目页面上显示具有类似最小植物药数量的杜松子酒列表。我觉得我很接近,但目前的输出并不正确。它实际上只是多次打印杜松子酒的名称。

  

杜松子酒负载(1.6毫秒)SELECT" gins"。* FROM" gins"内部联接   " gins_botanicals" ON" gins_botanicals"。" gin_id" =" gins"。" id"内   加入"植物药" ON"植物药"。" id" =   " gins_botanicals"" botanical_id"在哪里" botanicals"。" id" IN(4,10,3)   AND(" gins"。" id"!= $ 1)GROUP BY gins.id HAVING(COUNT(不同)   botanicals.id)> = 3)[[" id",2]]

我有三个型号;带有连接表的两个资源:

gin.rb

keyList.stream()
    .filter(s -> !s.matches("\\w"))
    .forEach(System.out::println);

botanical.rb

class Gin < ApplicationRecord
  belongs_to :distillery, inverse_of: :gins
  accepts_nested_attributes_for :distillery, reject_if: lambda {|attributes| attributes['name'].blank?}
  acts_as_punchable
  has_many :gins_botanical
  has_many :botanicals, through: :gins_botanical

gins_botanical.rb

class Botanical < ApplicationRecord
  has_many :gins_botanical
  has_many :gins, through: :gins_botanical

gins_controller

class GinsBotanical < ApplicationRecord
  belongs_to :gin
  belongs_to :botanical

所以在 def show @gin = Gin.friendly.find(params[:id]) @gin.punch(request) @meta_title = meta_title @gin.name @similiar_gins = Gin.joins(:botanicals).where("botanicals.id" => @gin.botanical_ids).where.not('gins.id' => @gin.id).having("COUNT(distinct botanicals.id) >= 3").group("gins.id") end 我试图计算当前@gin与所有其他@gins相比有多少匹配的植物,如果&gt; = 3则返回值。

在我看来:

show.html.erb

@similar_gins

我怀疑我的<% @similiar_gins.each do |gin| %> <%= @gin.name %> <% end %> 不正确......

1 个答案:

答案 0 :(得分:0)

Yes, I have the similar feature but I have implemented like below

@gin = Gin.find(params[:id])
if @gin.botanicals.count > 1
    @botanicals = @gin.botanical_ids
    @gin_ids = Botanical.select('distinct gin_id').where('gin_id IN (?)', @botanicals).limit(10)
    @ids = @gin_ids.map(&:gin_id)
    @similiar_gins = Gin.where('id IN (?)', @ids).where.not(id: @gin) #=> similar all without current gin
end

This code is converted from my code which is relation is category and jobs, if you need to see my code for showing the similar jobs then it is

def show
    @job = Job.find(params[:id])
    if @job.categories.count > 1
        @category = @job.category_ids
        @jobs = JobCategory.select('distinct job_id').where('category_id IN (?)', @category).limit(10)
        ids = @jobs.map(&:job_id)
        @releted_jobs = Job.where('id IN (?)', ids).where.not(id: @job)
    end
end

Hope it helps