Search code examples
ruby-on-railsmodelrails-migrations

Models need to be changed when migration files are changed?


I'm very new to Rails, and currently for our class, we have to create an application with databases.

I have a bunch of tables that have foreign keys to other tables, and I've defined these associations in the migration files (using execute("ALTER TABLE...")), but not in my models (I only have self.primary_key defined in my models).

My question is, since I've set these associations in my migrations, do I also have to set the associations in my models (i.e. has_may, belongs_to, validates_uniqueness_of, etc)?

I'll be creating an app that would allow user input, and these input would be inserted to the database.

Hoping that my confusion can be cleared up. Thank you!

Example

Migration file:

class CreateSchools < ActiveRecord::Migration[5.0]
  def up
    create_table :schools, {:id => false} do |t|
      t.integer :school_id
      t.string :school_name
      t.string :contact_number
      t.integer :a_id

      t.timestamps
    end
    execute "ALTER TABLE schools ADD PRIMARY KEY(school_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT a_id UNIQUE(a_id);"
    execute "ALTER TABLE schools ADD CONSTRAINT school_references_location FOREIGN KEY (a_id) REFERENCES locations(a_id) ON DELETE CASCADE ON UPDATE CASCADE;"
    change_column_null :schools, :school_name, false
    change_column_null :schools, :a_id, false
  end

  def down
    execute "ALTER TABLE schools DROP PRIMARY KEY;"
    execute "ALTER TABLE schools DROP FOREIGN KEY school_references_location;"
    execute "ALTER TABLE schools DROP INDEX a_id;"
    drop_table :schools
  end
end

Model:

class School < ApplicationRecord
  self.primary_key = :school_id
end

Solution

  • Yes you'll need to define the associations in Model as well.

    For all the rails applications,

    • Migrating and changing db according to associations is the first step.

    • Then add association statements in the models so that the associations from db can be accessed using simple methods. Like user.posts etc.

    • Adding association statements in Models provide you methods that generates queries according to the method called to retrieve data from db easily. You can also query db using join and select statements if you don't want to include association statements in Models.

    So, in short, designing schema to manage associations is necessary where as mentioning them in Model is not. But we do it to make our life and code simpler.