在Rails 3.1中,当类别通过 :has_many, :through 关联时,如何找到具有指定类别的商店

发布于 2024-12-20 02:33:50 字数 392 浏览 1 评论 0原文

在我的商店模型中,我有以下内容:

class Store < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations

  scope :by_categories, lambda{|category_ids|
    where(*stores have the following* => category_ids) unless category_ids.empty?
  }

我希望设置一个范围,可以向其发送多个或单个类别 ID,并让范围返回属于所有指定类别的商店。

谢谢您的关注。

In my Store model I have the following:

class Store < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations

  scope :by_categories, lambda{|category_ids|
    where(*stores have the following* => category_ids) unless category_ids.empty?
  }

I'm looking to setup a scope where I can send it multiple or a single category ID and have the scope return stores that belong to all the categories specified.

Thank you for looking.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

檐上三寸雪 2024-12-27 02:33:51
class Store < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations

  scope :by_categories, lambda { |category_ids|
    joins(:categorizations).where('categorizations.category_id' => category_ids) unless category_ids.empty?
  }
end

>> Store.by_categories([1,2])
=> SELECT "stores".* FROM "stores" INNER JOIN "categorizations" ON "categorizations"."store_id" = "stores"."id" WHERE "categorizations"."category_id" IN (1, 2)
class Store < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations

  scope :by_categories, lambda { |category_ids|
    joins(:categorizations).where('categorizations.category_id' => category_ids) unless category_ids.empty?
  }
end

>> Store.by_categories([1,2])
=> SELECT "stores".* FROM "stores" INNER JOIN "categorizations" ON "categorizations"."store_id" = "stores"."id" WHERE "categorizations"."category_id" IN (1, 2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文