我正在尝试获取商店订购的所有可用产品的总列表以及用户加入商店的时间,以便首先列出最近加入商店的用户,然后依此类推。请注意,无论该用户是否属于该商店,都需要显示所有产品(这些产品将在最后显示,并且优先级最低)。
Class User
has_many :memberships
has_many :stores, through: :memberships
has_many :active_memberships, -> {active}, class_name: "Membership"
has_many :active_stores, through: :active_memberships
end
Class Store
has_many :memberships
has_many :users, through: :memberships
has_many :active_memberships, -> {active}, class_name: "Membership"
has_many :active_users, through: :active_memberships
has_and_belongs_to_many :products, association_foreign_key: :product_id
end
Class Membership
belongs_to :users
belongs_to :stores
scope :active, -> {where(active: true).order(:created_at)}
end
Class Product
has_and_belongs_to_many :stores,
join_table: :product_stores,
foreign_key: :product_id
end
这是我到目前为止所要做的。
user = User.find(1)
ids = user.active_stores.ids
subscribed_store_products = Product.joins(stores: :memberships).where("stores.id = Any({#{ids}) AND memberships.user_id = 1").order("memberships.created_at")
non_susbscribed_store_products = Product.joins(:stores).where("stores.id != Any({#{ids})")
然后将两者合并以接收列表。我想知道是否可能缺少一些东西。