0

I have the following models

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

I want to query venues based which have the relation of Categories ID = (1)/(2) or (1 and 2)

How can i do a where query for the relation of a HABTM?

EDIT

Using the following query it solved the problem.

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

I want to exclude repetitive records from the query and a particular ID from the results?

---
- !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
Harsha M V
  • 54,075
  • 125
  • 354
  • 529

2 Answers2

2

Not sure if understanding you right. Plz provide sql code if you think this answer does not provide the right query But i think, it should be just

 Venue.joins(:categories).where(category_id: [1,2])
dre-hh
  • 7,840
  • 2
  • 33
  • 44
1

You can use below query to get venue details based on category

venues = Venue.joins(:categories_venues).where(:categories_venues => {:category_id => values})
Icicle
  • 1,174
  • 9
  • 13