Reputation: 23
I am working on determining the attitude of a post using AFINN 111, which can be found here. Whenever one of these words are mentioned in the post, their corresponding values are selected and added, to give the cumulative score, which helps in determining the nature of the post, whether +ve or -ve.
I have an array content = ["bad", "bad", "dog"]
.
I want to get the total score for the words being used in this post. so, i fire a db query.
score = Sentiment.where(word: content).pluck(:value).inject(:+)
The result i get is -3. The word "bad" has a corresponding score of -3. since the word "bad" repeats two times, i want the resultant score to be -6.
I tried firing this in rails console to check how many objects are being returned.
Sentiment.where(:id => [1,1])
returns only one object...Is there any option that will allow the duplicate values to be returned?
One fairly simple solution is to iterate through the array.
score = 0
content.each do |word|
score += Sentiment.where(word: word).pluck(:value).first
end
but this will involve firing n number of queries, rather than finishing the job with a single query... Is there any other way of achieving this?
Upvotes: 1
Views: 74
Reputation: 27463
Another solution with one query:
content = ['bad', 'bad', 'dog']
sentiments = Sentiment.where(word: content).group_by(&:word)
score = 0
content.each do |word|
score += sentiments[word].score if sentiments[word]
end
score #=> -6
Upvotes: 1