Normalization of data in rails

I created a rail model by doing

script/generate model Customer name:string address:string city:string state:string zip:integer [...]

I populated the database with 5,000 clients and started building my application. Now I realized that my model is not normalized: I often have several clients at the same address! If I want to do something at an address, such as mail, this will cause problems. What I would like to have is a model Address, model Customerand model Mailing.

Is there a way for rails to normalize an existing model by dividing it into two models? Or should I just write a script to normalize my existing data, and then generate new models accordingly?

+3
source share
2 answers

, . , , .

script/generate model address customer_id:integer address:string city:string state:string zip:integer

class CreateAddresses < ActiveRecord::Migration
  def self.up
    create_table :addresses do |t|
      t.integer :customer_id
      t.string :address
      t.string :city
      t.string :state
      t.integer :zip_code
      t.timestamps
    end

    # move customer address fields to address table
    Customer.all.each do |c|
      Address.create({
        :customer_id => c.id,
        :address => c.address,
        :city => c.city,
        :state => c.state,
        :zip => c.zip
      })
    end

    # you'll have to write your own merge script here
    # use execute("your sql goes here...") if you can't do it with ActiveRecord methods

    # remove old customer address columns
    remove_columns(:customers, :address, :city, :state, :zip)

  end

  def self.down

    # here you will define the reverse of the self.up method

    # re-add the address columns to the user table

    # repopulate the customer table with data from the address table

    drop_table :addresses
  end
end

+8

Rails . Address , .

, , :

class Person < ActiveRecord::Base
  has_many :addresses
end

class Address < ActiveRecord::Base
  belongs_to :person
end
+4

Source: https://habr.com/ru/post/1740872/


All Articles