0

I'm using a model to track my dupermarket purchases. The schema of the table representing items is:

CREATE TABLE "items"
 ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  "barcode" varchar,
  "brand" varchar,
  "gendesc" varchar,
  "size" float,
  "unit_id" integer,
  "created_at" datetime NOT NULL,
  "updated_at" datetime NOT NULL);

Inclusion of gendesc (generic description, as a varchar) was a modeling mistake; I should have made this a foreign key, with the text descriptions in an additional table, as different brands of the same thing are equivalent for some but not all purposes of analysis. So I want to replace the gendesc column with a gendescs_id column that is a foreign key for some gedescs table which would be equivalent to something created thus:

create table gendescs (id integer primary key, gendesc varchar);

select into gendescs(gendesc) distinct gendesc from items;

Is there a sequence of Rails migrations which does something like this?

Lori
  • 1,392
  • 1
  • 21
  • 29

1 Answers1

1

Ideal flow should be like this:

  1. Create gendescs table. I will prefer not to name column as same as table name.

    rails g model Gendesc value:string

  2. Add foreign key

    rails g migration AddGendescToItem gendesc:references

  3. Run rake db:migrate

  4. If you have data in items.gendesc column then you need to create entries for them in gendescs table. Run following code in rails console.

    Item.find_each do |i|
      g = Gendesc.find_or_create_by(value: i.gendesc)
      i.update(gendesc_id: g.id)
    end
    
  5. Remove column gendesc from items table How to remove a column from my Rails model?

  6. add belongs_to relationship to item model

    belongs_to: :gendesc

Community
  • 1
  • 1
dnsh
  • 3,516
  • 2
  • 22
  • 47