2013-11-20 12 views

risposta

33
User.update_all({name: 'test'},{name: 'test1'}) # deprecated since Rails 4 

o

User.where(name: 'test1').update_all(name: 'test') 
+5

Penso che le prime opzioni siano effettivamente deprezzate ora. – simonmorley

+12

Può confermare dopo 15 minuti di debug del vecchio codice, la prima riga è deprecata in Rails 4 (vorrei che avessero dato un avvertimento!). – Noz

+1

Vorrei anche sottolineare che questa istruzione viene eseguita come clausola di aggiornamento singolo dove invece di una singola selezione dove e quindi un'istruzione di aggiornamento. – Aaronias

5
User.where("name like 'test1'").update_all("name = 'test'") 
+0

che avrebbe generato 'utenti Aggiornare Imposta name = "test" WHERE name LIKE "test1"' si è lo stesso resu lt, ma non la stessa query l'OP ha richiesto EDIT: non lo stesso risultato, LIKE è caseunsensitive, aggiornerà anche le righe con il nome TEST1 ad esempio – arieljuod

0

@Vijay Chouhan, Prova questo, Questo darà la stessa query richiesta.

User.where (nome: "test") -> Questo vi darà la matrice ActiveRecord :: Relation quindi convertirlo in semplice array come

u = User.where (nome: "test ") .to_a

se u.count è uguale a 1, quindi utilizzare questo come una domanda finale -

**** finale Query -> **** User.where (nome:" test "). a_a.first.update (nome:" test1 ")

altro u.count è maggiore di 1 poi fare un ciclo come

**** Query finale -> **** User.where (nome: "test") to_a.each {|. x | x.update (nome: "test1")}

Può essere utile a voi ....

       **OR** 

Hey @Vijay Chouhan,

Proprio ora ho trovato la soluzione migliore che è -

User.where (nome: test) .update_all ("name = 'test1'")

Problemi correlati