Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Updating fields in different models through a rake task


I have a products model, with a categories column. Users were able to save multiple comma separated values in the same field.

I just finished refactoring my DB so by creating a categories table, and a categories_products join.

How can I updated my categories model with the categories while also updating the join table with the corresponding category_id and product_id.

This is what I have in a rake task so far, which basically just separated the categories from the products table.

Product.find(:all).each do |k|
  k.categories.split(",").each do |w|
    puts k.id + " " + w
  end
end

Solution

  • This is a good start. Assuming you are using a HABTM association and that there is no collision on the word category (ie. your new table is something like Cats):

    Product.find(:all).each do |product|
      product.categories.split(",").each do |category|
        if Cats.exists?(name: category)
          product.cats.create(name: category)
        else
          product.cats << Cats.find_by_name(category)
        end
      end
    end
    

    Also, because this is a one-time operation, rather than a task that will be executed many time, this is probably a better candidate for a DB migration. That means it needs to inside an up/down or change grouping, and be have an inverse function written.