1

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

2
  • 1
    Please share your expected result. Commented Sep 2, 2015 at 8:55
  • '<Celebrity id: 7, name: "Di Caprio", gender: false, category_id: "1", , image_file_name: "422817.jpg", image_content_type: "image/jpeg", image_file_size: 132673, image_updated_at: "2015-07-20 08:20:53",vote_count=>2>]' This is what i am expecting Commented Sep 2, 2015 at 9:03

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

+apneadiving is right. use counter_caches

3 Comments

wow... just do this and youre fine yerb.net/blog/2014/03/13/…
after adding "votes_count" attribute to my table its fixed, but in voting action I can't able to vote for a celebrity, getting this error 'missing attribute: votes_count'.My code: 'celebrity = Celebrity.find(params[:id]) vote = Vote.build(celebrity_id: celebrity.id, :id => params[:vote]) respond_to do |format| if vote.save format.html { redirect_to ranking_url } format.json { render json: vote, status: :created } else format.html { render action: 'new' } format.json { render json: vote.errors,status::unprocessable_entity} end end'
Pastebin Or pastie.org

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.