Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query object only if child has particular attribute

I have a few models defined as follows:

class Question < ActiveRecord::Base
  has_many :skill_tags, as: :skillable
end

class SkillTag < ActiveRecord::Base
  belongs_to :skillable, polymorphic: true
  belongs_to :skill
end

class Skill < ActiveRecord::Base
  has_and_belongs_to_many :skill_tags
end

I want to get an array of all Question objects with a particular skill associated with them.

For example - I want all questions that have a skill tag with a skill_id of 16, 34, and 89. These could be in an array. What's the most Rails-friendly way of achieving this? I can think of some more 'brute-force' approaches, but I'd like it to be as clean as possible.

like image 781
opticon Avatar asked Jan 26 '26 17:01

opticon


1 Answers

Something like this should do the trick:

Question.joins(:skill_tag).where(:skill_tags => {:skill_id => [16, 34, 89]})
like image 177
Slicedpan Avatar answered Jan 29 '26 07:01

Slicedpan