-1

Is there any logic to update ActiveRecord Query Record's field from 1 to n.

@user = User.where(country: 'US')

Need to update above @user's field count from 1 to n.

Thanks in Advance.

EDIT:

Need to update all record's - field is count.

AR Query will return array, need to each element in array(tuple)'s count field from 1 to n

Example: AR Query Output: [User1, User2, User3, User4, ...]

User1's count field must be updated to 1

User2's count field must be updated to 2 and so on.

  • 1
    Do you mean user has a count field on the database? – Ursus Sep 21 '18 at 11:52
  • Which user field you want to update ? And change `@user` to `@users` for better name convention. – Tanay Sharma Sep 21 '18 at 11:52
  • I don't understand your question. Update which field? Of a single record, or a collection of records? *Possibly* the answer you're looking for us to use `update_all`?? – Tom Lord Sep 21 '18 at 11:56
  • `User.where(country: 'US')` will not return a single user but an array of users. What do you want to update? All users in that array? To the same `n`? – spickermann Sep 21 '18 at 11:57
  • Since he wrote `without looping` in the question title i assume he asking for `User.where(country: 'US', id: 1..N).update_all(whatever: value)` – D1ceWard Sep 21 '18 at 12:01

1 Answers1

1

Depending on your database you can do it using SQL but ActiveRecord's Relation won't support that.

Check this out: Update SQL with consecutive numbering

To execute SQL you can use:

User.connection.execute("YOUR SQL HERE...")
Rodrigo
  • 5,435
  • 5
  • 42
  • 78