counting the result of a join

28 views
Skip to first unread message

Ronald Fischer

unread,
Jul 2, 2014, 7:59:08 AM7/2/14
to rubyonra...@googlegroups.com
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).

--
Posted via http://www.ruby-forum.com/.

Ronald Fischer

unread,
Jul 10, 2014, 12:17:00 PM7/10/14
to rubyonra...@googlegroups.com
The solution is found here:

http://stackoverflow.com/questions/24607428/rubyonrails-counting-the-result-of-a-join

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?
Reply all
Reply to author
Forward
0 new messages