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に次の作業コードを追加しました:いない配列内のIDを持つ製品を検索するに

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

を、あなたはこれを行う必要があります。

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

しかし、製品がユーザーに属しているので、あなたは、単に行うことができます

Product.where('user_id != ?', current_user.id) 
あなたはまた、そうのような notメソッドを使用することができます

:あなたは、ベース製品が他のいくつかのリストからになりたい場合は、これを助けることができる

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) 

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

編集

some_listActiveRecord::Relationの場合は、単純に次のように設定できます。

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

あなたの答えをありがとう。これまでのところ理解していますが、 '@product_rec'は' product_rec'( 'predictor-gem'からのプロダクトIDの配列です)に基づいている必要があります。これから' current_user'の製品コレクションを減らしたいと思います。私はあなたのコードの中にそれを組み込む方法を知らない。 –

+0

@SebastianPlasschaert、 'current_user'に属する製品を除くすべての製品が必要ですか?もしそうなら、 'array'変数をどのように取得しているのか見てください。 – Humza

+0

これはすべての製品に基づくのではなく、あらかじめ選択された '@ product_rec'のセット(' product_controller.rb'を参照)で行うべきです。私はすでに '@ product_rec.where()'を試しましたが、それはうまくいかないようです... –

関連する問題