user1934428
user1934428

Reputation: 22225

RubyOnRails: counting the result of a join

(CROSSPOSTING NOTE: I have already posted this question a couple of days ago at https://www.ruby-forum.com/topic/5048524 without getting a response).

Using RubyOnRails 4, with Ruby 2:

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 :kind.

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=#{dict.id} and cards.id=idioms.card_id and kind=#{kind}").
        count > 0
end

This works, but can it be done better? I also tried to omit at least one of the id comparision by doing something like:

dict.cards.where("cards.id = ...").count > 0

but this doesn't work ("count" is not applicable in this case).

Upvotes: 1

Views: 40

Answers (1)

Arctodus
Arctodus

Reputation: 5847

You can at least improve this by going through the associations instead of adding where conditions on the IDs explictly:

Class Dict < ActiveRecord::Base
  has_many :cards
  has_many :idioms,  through: :cards

  def has_kind?(kind)
    idioms.where(kind: kind).exists?
  end
end

Upvotes: 2

Related Questions