0

我打電話給一組推薦產品(基於predictor-gem),並且想要排除該組中的current_user的產品。我認爲我正在使用它的適當條件(" != ?"),但只是不正確的方式。 @products_rec應該給最後一個數組。如何從find方法中排除id的數組?

下面是我的product_controller.rb具體代碼:

​​

,這裏是我的模型,product.rb:

class Product < ActiveRecord::Base 

    include Reviewing 
    include PublicActivity::Model 
tracked 

extend FriendlyId 
friendly_id :name, use: [:slugged, :finders] 

belongs_to :category 

belongs_to :benefit 

has_many :subscriptions 
has_many :users, through: :subscriptions 

has_many :benefits 
has_many :projects, through: :benefits 

belongs_to :user 

validates :name, presence: true, length: { maximum: 200 } 
validates :gtin, presence: false 
validates :content, presence: false, length: { maximum: 2000 } 
validates :video, presence: false 
validates :tag, presence: false 
validates :project, presence: false 
validates :category, presence: false 
validates :user, presence: false 

has_attached_file :image, :styles => { :medium => "680x300>", :thumb => "170x75>" } 
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/ 

end 

我要排除的產品從current_user的基礎上,通過用戶訂閱(請參閱模型)。

我該如何得到這個工作,任何想法?

最終代碼: 基於對@Humza答案,我已經添加了以下工作代碼我product_controller.rb:不是在陣列

recommender = ProductRecommender.new 

    products = current_user.products.select("id") 

    @product_rec = (recommender.similarities_for("product-#{@product.id}")).map {|el| el.gsub(/(.*\-)[^\d]*/, "")} 
    @products_rec_array = Product.find(@product_rec) 
    @products_rec = Product.where(id: @products_rec_array).where.not(id: products) 
+0

您正在使用哪個版本的Rails? – Pavan

+0

我正在使用Rails 4 –

+0

@Pavan關於如何解決此問題的任何想法? :) –

回答

1

要查找產品ID,你必須這樣做:

array = current_user.products.pluck(:id) 
Product.where('id NOT IN (?)', array) # '?' is surrounded by paranthesis 

但是,由於產品屬於用戶,你可以簡單地做

Product.where('user_id != ?', current_user.id) 

您還可以使用not方法,像這樣:

Product.where.not(id: array) 
Product.where.not(user_id: current_user.id) 

編輯:

如果你想在基礎產品是從其他列表,這可以幫助:

base_product_ids = some_list.map(&:id) # assuming this is an Array 
Product.where(id: base_product_ids).where.not(user_id: current_user.id) 

如果some_listActiveRecord::Relation,您可以簡單地完成:

some_list.where.not(user_id: current_user.id) 
+0

謝謝你的回答。我目前瞭解它,但'@ products_rec'需要基於'@ product_rec'(這是一個來自'predictor-gem'的產品ID數組),我想從中減去'current_user'的產品集合。我不知道如何將其納入您的代碼中。 –

+0

@SebastianPlasschaert,你想要除屬於'current_user'的所有產品,對吧?如果是的話,看看我如何得到'array'變量。 – Humza

+0

它不應該基於所有產品,而是基於預先選擇的集合「@ product_rec」(請參閱​​'product_controller.rb')。我已經嘗試過@ @ product_rec.where()',但這似乎不起作用... –