0

Say I have a db table called fruit like this:

id  name
1   ““
2   “"
3   ““
4   ““
5   ""
6   melon

I need to write a migration to change the empty strings to null without affecting melon in this case.

Would it be something on these lines?

def change
  update_column fruits, :name, null if :name => ""
end

Pretty basic stuff I guess but I'm kinda stuck here. What is the best approach here?

Jax
  • 1,839
  • 3
  • 18
  • 30
  • 2
    why not just do an `update_all`, `Fruit.where(name: "").update_all(name: nil)` – lusketeer Jun 09 '16 at 11:22
  • @lusketeer you mean use that in the migration? – Jax Jun 09 '16 at 11:24
  • anywhere, rails console, migration, you don't really need a migration, but if want to keep things consistent, add it to migration – lusketeer Jun 09 '16 at 11:25
  • @lusketeer yeah consistency is the name of the game here :-), that worked a treat in a migration, throw it in an answer and I'll accept it. – Jax Jun 09 '16 at 11:31

3 Answers3

0

in console development and production as well:

Fruit.all.each do |fruit|
  if fruit.name == ""
    fruit.name = nil
    fruit.save
  end
end
Sean Magyar
  • 2,360
  • 1
  • 25
  • 57
0

Use the normal command to generate a migration;

rails g migration xxxxx

And then add:

def change
  execute "UPDATE fruits SET name = NULL WHERE name = '' "
end 
davegson
  • 8,205
  • 4
  • 51
  • 71
VijayGupta
  • 637
  • 3
  • 11
0
Fruit.where(name: "").update_all(name: nil)

rails console, migration, anywhere you can excute it. You don't really need a migration, but if want to keep things consistent, add it to migration

lusketeer
  • 1,890
  • 1
  • 12
  • 29