2

I have to update multiple objects with multiple values like this:

project.update(user_attributes: task_ids.collect { |id| { 'task_id': id } })

But the above code will result in n + 1. Any ideas in order to avoid n + 1 here?

Ahmad hamza
  • 1,816
  • 1
  • 23
  • 46
  • 3
    Is this code even valid? I mean - you are setting `task_id` for all users to `12213`, then `12323`, etc. to finally set it to `34563`. Is there any reason for that? – MrShemek Apr 16 '18 at 12:20
  • Yes you are right. I was trying to write in a simpler way but here is the original code, – Ahmad hamza Apr 16 '18 at 12:37
  • Why would here be `n + 1`? I dont see it – Martin Apr 16 '18 at 12:44
  • Calling: `project.update_all(user_attributes: VALUE)` should execute only one query: `UPDATE 'projects' SET 'projects.user_attributes' = VALUE` (there might be additional `where` clause) – MrShemek Apr 16 '18 at 12:45
  • Here `VALUE` is dynamic. – Ahmad hamza Apr 16 '18 at 12:53
  • Okay, so the problem is that you are trying to set different values for different projects, right? Not the same value (for instance, array of IDs) for all of the projects? – MrShemek Apr 16 '18 at 13:03
  • its like updating all users of that project with the task ids and if any user dont exist then it should create the user. – Ahmad hamza Apr 16 '18 at 13:11
  • @MartinZinovsky because if there are any users which are not present in the db then it will try to create those users. – Ahmad hamza Apr 16 '18 at 13:19
  • @Ahmadhamza can you share the relation between `Project --> User --> Task` if I'm not mistaken its many to many between `Project and User` `one to many between Project and Task` and `many to many between User and Task` – ashwintastic Apr 17 '18 at 09:38
  • @Ahmadhamza Did you find a solution to your n+1 problem? – Darkfish Oct 21 '19 at 05:50
  • @Darkfish No i dint find any. – Ahmad hamza Oct 21 '19 at 07:45

0 Answers0