database maintenance, updating tables having has_many_through relationships

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

database maintenance, updating tables having has_many_through relationships

fugee ohu
I have a table of items and a table a pictures table They relate to each other through an item_pictures table having model name item_picture All my items have titles but I just added captions to my pictures table and now I wanna update all the records in pictures to set the captions column to the value of each picture's item's title

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/c5a41104-770c-48ba-abc9-450e4e1096f5%40googlegroups.com.
Reply | Threaded
Open this post in threaded view
|

Re: database maintenance, updating tables having has_many_through relationships

Walter Lee Davis
Is this something you'd like to maintain automatically, or just do once? You remember how to use the console (if the latter)?

Picture.find_each do |pic|
  pic.update caption: pic.item.caption
end

If you want to do it every time you save a new picture, then you can add a similar helper to the Picture model, and call it in a before_save callback:

def cache_caption
  self.caption = item.caption
end

before_save :cache_caption

Walter

> On Sep 14, 2019, at 4:45 AM, fugee ohu <[hidden email]> wrote:
>
> I have a table of items and a table a pictures table They relate to each other through an item_pictures table having model name item_picture All my items have titles but I just added captions to my pictures table and now I wanna update all the records in pictures to set the captions column to the value of each picture's item's title
>
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
> To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/c5a41104-770c-48ba-abc9-450e4e1096f5%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/8113E780-69A3-4222-8AF7-2D7F30401CEB%40wdstudio.com.