Answer the question
In order to leave comments, you need to log in
[Rails] How to correctly update the fields in the database when sorting elements (array)?
Hello.
A line like this is sent in the post request:
image_pos[0][id] 1
image_pos[1][id] 2
image_pos[2][id]
3
...
, which I have already done, but how to select only those records that I change, and not all. And substitute the corresponding values in image_pos.
Actually in the array of records like this: [{"image_pos": 1},{"image_pos": 2},{"image_pos": 2}]
params[:image_pos].each_with_index do |id, index|
Image.update_all({image_pos: index})
end
Answer the question
In order to leave comments, you need to log in
update_all changes the value of all records to the specified one. That is, you first put position 1 for all pictures, then 2 for all, and so on.
If in your loop id is the id of the picture, then you need something like:
ActiveRecord::Base.transaction do
params[:image_pos].each_with_ibdex do |id, index|
Image.find(id).update_attributes(image_pos: index)
end
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question