Rails HABTM: Select everything a that a record 'has'

218 views Asked by At

I have three tables: projects, technologies, and projects_technologies (a map from project IDs to/from technology IDs). I have two models: projects and technologies. Projects have and belong to many (HABTM) technologies and vice versa. Now I'm trying to get all the names (or active records, if there's a way to do that) of technologies that belong to a given project. Here's the SQL statement I've made, using 5 as the given project ID:

SELECT name FROM technologies WHERE id IN (
  SELECT projects_technologies.technology_id FROM projects_technologies
  WHERE projects_technologies.project_id = 5
);

I could just connect to the database and run the query, but since I already have the models set up with HABTM relationships, I'm wondering if there's a "Rails way" to execute this. I've been looking at this documentation, http://guides.rubyonrails.org/active_record_querying.html, but I can't figure out if and how I can apply that to this kind of query.

UPDATE

Turns out all I needed was this:

Project.find(5).technologies
1

There are 1 answers

2
Rajdeep Singh On BEST ANSWER

The equivalent active record query would be

Technology.select('name').where("id IN (?)", ProjectTechnology.where("project_id = ?", 5).pluck(:technology_id))

Hope this helps!