Counting the result of a join

(Crossposting note: Since I didn’t get any response here, I posted this
also on

I have in my model :dicts, :cards and :idioms. Each Dict has many Cards
and each Cards has many Idioms. Also, :idioms has an Integer column

I would like to find out, whether a certain dict object has at least
one Card which has at least one Idiom where :kind has a certain value.

This is my (working) code:

def has_kind?(dict,kind)
Card. joins(:idioms). where(“dict_id=#{} and and kind=#{kind}”). count > 0

This works, but can it be done better? I also tried to omit at least one
of the id comparision by doing something like:“ = …”).count > 0

but this doesn’t work (“count” is not applicable in this case).

The solution is found here:

Basically, I need to specify in my :dicts model, that there is an
association to :cards

in class Dict:

has_many :idioms, through: :cards

After this, I can do:

idioms.where(kind: kind).exists?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs