Y
Y
yogaku2014-09-02 23:21:06
JavaScript
yogaku, 2014-09-02 23:21:06

[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


UPD: Really nobody faced this task?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Vsk, 2014-09-03
@viktorvsk

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

But in this case, index is not what was specified in the form, but simply in order from 1 to the number of image_pos.
In general, the final entry depends on your image_pos hash

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question