Acts_as_list: update all items?

Hi there

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

Joshua M. wrote:

Hi there

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

Alex W. wrote:

Product.find(:all) do |p|
^
ain’t that with .each?

Maybe I have been reading find() do and writing find().each do…


Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!

Phlip wrote:

Alex W. wrote:

Product.find(:all) do |p|
^
ain’t that with .each?

Maybe I have been reading find() do and writing find().each do…


Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!

heh, um yeah. it’s late :stuck_out_tongue:

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

Lol thank you guys, I nearly became nuts because of the missing each! %)
Anyway, there’s still a missing “do” somewhere… Anyone can find it?
:wink:

Joshua M. wrote:

Lol thank you guys, I nearly became nuts because of the missing each! %)
Anyway, there’s still a missing “do” somewhere… Anyone can find it?
:wink:

Everybody go do something physical to burn off the coffee…

…then go to bed!

Discretion is the better part of valor! Live to program another day!


Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!