Skip to content

Instantly share code, notes, and snippets.

@sergiomaia
Last active November 25, 2021 12:36
Show Gist options
  • Save sergiomaia/5e3b5d8e6e30f09607a5f5be87a46f90 to your computer and use it in GitHub Desktop.
Save sergiomaia/5e3b5d8e6e30f09607a5f5be87a46f90 to your computer and use it in GitHub Desktop.
# tenho a seguinte situação:
def update
ids = params["_json"].map { |hash| hash["id"] } # --> return [10, 20, 30, 40, 50]
positions = params["_json"].map { |hash| hash["position"] } # --> return [0, 1, 2, 3, 4]
query = MyQueryQuery.new
query.visible = true
query.active = true
available = query.fetch.map(&:id)
::Model.where(id: (ids & available))
.update_all(show_home: true, updated_at: DateTime.now)
end
# a meneira acima é forma que meu método funciona atualmente,
# o problema é que surgiu a necessidade de atualizar mais um campo no meu Model, seria o campo "position",
# com os valores do Array positions (linha 5). Ou seja, para cada ID atualizar o position,
# ex: {ID 10 - position 0} , {ID 20 - position 2}, {ID 30 - position 3} ....
# a quantidade de IDS sempre será a mesma quantidade de positions.
@sergiomaia
Copy link
Author

Reolução:

positions = params['_json']

positions.each do |p| 
    model = ::model.find(p['id'])
    model.update(position: p['position'])
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment