gpt4 book ai didi

ruby-on-rails - 基于多种模型的Rails Join

转载 作者:行者123 更新时间:2023-11-29 13:28:16 25 4
gpt4 key购买 nike

我有四个模型:UserProductPurchaseWatchedProduct

我正在尝试获取满足以下条件之一的产品列表:

  1. 我创造了产品。
  2. 我买了产品。
  3. 该产品是免费的,我已经对其“加注星标”或“观看”了。

这是我目前所拥有的:

class User < ActiveRecord::Base
...

def special_products
product_ids = []

# products I created
my_products = Product.where(:user_id => self.id).pluck(:id)
# products I purchased
my_purchases = Purchase.where(:buyer_id => self.id).pluck(:product_id)
# free products I watched
my_watched = WatchedProduct.where(:user_id =>self.id).joins(:product).where(products: { price: 0 }).pluck(:product_id)

product_ids.append(my_products)
product_ids.append(my_purchases)
product_ids.append(my_watched)

product_ids # yields something like this => [[1, 2], [], [2]]

# i guess at this point i'd reduce the ids, then look them up again...

product_ids.flatten!
product_ids & product_ids
products = []
product_ids.each do |id|
products.append(Product.find(id))
end
products

end
end

我想要做的是获取 Product 模型列表,而不是 ID 列表或 ActiveRecord 关系列表。我对联接还很陌生,但有没有一种方法可以在一次联接中完成所有这些操作,而不是 3 个查询、减少和重新查找?

最佳答案

首先我喜欢添加一些作用域

class Product < ActiveRecord::Base
scope :free, -> { where(price: 0) }
scope :bought_or_created_by, lambda do |user_id|
where('user_id = :id OR buyer_id = :id', id: user_id)
end
end
class WatchedProduct < ActiveRecord::Base
scope :by_user, ->(user_id) { where(user_id: user_id) }
end

然后是查询

special_products = (Product.bought_or_created_by(id) + Product.joins(:watched_products).free.merge(WatchedProduct.by_user(id)).uniq

这将使用 2 个查询返回一组独特的产品。

关于ruby-on-rails - 基于多种模型的Rails Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29398755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com