Saravana
Saravana

Reputation: 115

append data to an array rails 4

I need to append data to a variable

@celebrity = Celebrity.includes(:category).where('category_id = ?', params[:id])
test =[]
@celebrity.each do |celeb|
  @vote = Vote.where('celebrity_id = ?', celeb).count
  test  << {vote_count:@vote}
end

when i debug 'test',

abort test.inspect

I am getting the result of

[{:vote_count=>2}, {:vote_count=>1}, {:vote_count=>0}]

but, my question is how can I append vote_count to @celebrity , can anyone please help me out

Upvotes: 1

Views: 57

Answers (2)

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

@celebrity.each do |celeb|
  celeb["vote_count"] = celeb.votes.count
end

+apneadiving is right. use counter_caches

Upvotes: 0

apneadiving
apneadiving

Reputation: 115541

You should not do it this way, its terrible in terms of performance.

If you setup a counter_cache properly (see ref), you'd have data right away in your model instances as expected

Upvotes: 2

Related Questions