简体   繁体   中英

Add multiple HABTM

I have a has_and_belong_to_many relation between Talk and RatingQuestion . I want to add (or remove) the relation on hundreds of records at once.

I'm using a for loop, but it takes some time since there could be possibly thousands of talks. Any idea how I could improve the code below?

rq = RatingQuestion.find(rating_question_id)
talks.each do |talk|
  talk.rating_questions << rq unless talk.rating_questions.include?(rq)
end

You should move long-running tasks into a background job queue. Database writes are generally very expensive, so as you get into the mentioned thousands of associations, your request very well may time out.

You could probably improve the performance of this through bulk inserting, which bunches all your inserts into larger INSERT calls to the database.

However , this is a big indicator that you're going about the structure of your app poorly. Do all these records have to exist in the database? Could they be created as they're answered or manipulated instead of all up-front?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM