I have the models product and images, where a product may have as many
images as it wants. I already have several products and images, and now
I want to make the listable. So I created a migration that adds a field
“position” to the images table.
So far, so good. But I also want the migration to update the position
fields of every image, so the images of product X have the numbers 1, 2,
3 etc. in their position fields.
I have the models product and images, where a product may have as many
images as it wants. I already have several products and images, and now
I want to make the listable. So I created a migration that adds a field
“position” to the images table.
So far, so good. But I also want the migration to update the position
fields of every image, so the images of product X have the numbers 1, 2,
3 etc. in their position fields.
How can I do that?
Thanks for help,
Josh
You can simply embed ruby in your migration:
def self.up
add_column :images, :position, :integer
Product.find(:all) do |p|
p.images.each_with_index |img, i|
img.update_attribute(:position, i)
end
end
end
def self.up
add_column :images, :position, :integer
Product.find(:all).each do |p|
p.images.each_with_index |img, i|
img.update_attribute(:position, i)
end
end
end