Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails where clause for :through association

I have the following associations...

class Event < ActiveRecord::Base
  ...
  has_many :tags, :through => :taggings

This allows me to do something like Event.last.tags and see all tags associated with an email. I'm trying to come up with a where clause for tags where I can do something like...

Event.where tag: 'my_tag'

When I do this I get:

2.1.3 :020 > Event.where tags: 'test'
  Event Load (0.4ms)  SELECT `events`.* FROM `events` WHERE `events`.`tags` = 'test'
ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'events.tags' in 'where clause': SELECT `events`.* FROM `events`  WHERE `events`.`tags` = 'test'
like image 209
Mark Locklear Avatar asked Nov 15 '25 11:11

Mark Locklear


1 Answers

Is this what you're looking for?:

Event.includes(:tags).where(tags: {name: 'my_tag'})

This will get all events with tags where tags' name is 'my_tag'. Change name with the appropriate column name which exists in tags table for which you're trying to run query for.

like image 199
Surya Avatar answered Nov 17 '25 06:11

Surya