Rails查询基于hasManyBelongsToMany关系

时间:2014-08-25 06:31:48

标签: ruby-on-rails ruby-on-rails-4 has-and-belongs-to-many

我有以下型号

venues(id, name, ....)
categories(id, name, ....)
categories_venues(id, venue_id, category_id)

我想查询具有Categories ID = (1)/(2) or (1 and 2)

关系的场地

如何查询HABTM的关系?

修改

使用以下查询解决了问题。

venues = Venue.joins(:categories_venues).where(:categories_venues => {:category_id => values})

我想从查询中排除重复记录,并从结果中排除特定ID?

---
- !ruby/object:Venue
  attributes:
    id: 2
    name: Ooty
    slug: ooty
    created_at: 2014-06-21 22:10:52.000000000 Z
    updated_at: 2014-07-05 17:33:26.000000000 Z
- !ruby/object:Venue
  attributes:
    id: 4
    name: Munnar
    slug: munnar
    created_at: 2014-08-25 03:42:13.000000000 Z
    updated_at: 2014-08-25 03:42:13.000000000 Z
- !ruby/object:Venue
  attributes:
    id: 2
    name: Ooty
    slug: ooty
    created_at: 2014-06-21 22:10:52.000000000 Z
    updated_at: 2014-07-05 17:33:26.000000000 Z

2 个答案:

答案 0 :(得分:2)

不确定是否理解你。如果您认为此答案未提供正确的查询,则Plz会提供sql代码 但我想,它应该只是

 Venue.joins(:categories).where(category_id: [1,2])

答案 1 :(得分:1)

您可以使用以下查询根据类别获取场地详情

venues = Venue.joins(:categories_venues).where(:categories_venues => {:category_id => values})