logo
down
shadow

How to add foreign key in migration where reference table has no id column


How to add foreign key in migration where reference table has no id column

Content Index :

How to add foreign key in migration where reference table has no id column
Tag : ruby-on-rails , By : Cesar Sanz
Date : January 11 2021, 03:34 PM

This might help you You should be able to use primary_key option in your foreign key migration, it defaults to column id and that is the reason, why you are getting an error:
add_foreign_key :test_models, :reasons, column: :reason_code, primary_key: :code

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

In Rails, how do I create a migration that will add a column/foreign key to a table that is of the same type as that tab


Tag : postgresql , By : abuiles
Date : March 29 2020, 07:55 AM
wish of those help I’m using Rails 4.2.3. How do I create a migration that will add column to a table that is of the same type as the table? Further, how do I add a foreign key (it is fine if the column is NULL)? I tried this , I think you need to do it "manually":
add_column :my_objects, :linked_my_object_id, :integer
add_index :my_objects, :linked_my_object_id
add_foreign_key :my_objects, :my_objects, column: :linked_my_object_id
belongs_to :linked_my_object, class_name: MyObject
has_many :my_objects, foreign_key: :linked_my_object_id

set the column code as foreign key on table with a reference to another table


Tag : sql-server , By : user119605
Date : March 29 2020, 07:55 AM
hop of those help? A foreign key is a reference to another table. It is used to establish relationships between tables. For example, relationship between tbl_Shoe and tbl_PLAYER table. One tbl_Shoe can have multiple codes. The Primary key of tbl_Shoe becomes foreign key of codes of another table which is the tbl_PLAYER.so here is my answer.
 create table tbl_Shoes
create table tbl_PLAYERS

How to add reference to another table column as foreignKey in the migration using Sequelize


Tag : node.js , By : Stephen Dewar
Date : March 29 2020, 07:55 AM
wish helps you Here is the migration workflow:
Generate models and migration files using sequelize-cli. Define the association between Student and Project based on your business requirements. Based on the associations between the models, modify the migration files, add the foreign keys(add student_id column to Project table). For your case, Project table has a student_id column as its foreign key reference to the Student table's _id column.
module.exports = (sequelize, DataTypes) => {
  const Student = sequelize.define('Student', {
    _id: {
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    email: {
      type: DataTypes.TEXT,
      allowNull: false,
      unique: true,
    },
    dateOfBirth: {
      type: DataTypes.DATEONLY,
      allowNull: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
  });

  Student.associate = function(models) {
    Student.hasMany(models.Project, {
      foreignKey: 'student_id',
      as: 'projects',
    });
  };
  return Student;
};
module.exports = (sequelize, DataTypes) => {
  const Project = sequelize.define('Project', {
    project_id: {
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    creationDate: {
      type: DataTypes.DATEONLY,
      allowNull: true,
    },
    repoUrl: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    liveUrl: {
      type: DataTypes.TEXT,
      allowNull: true,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
    },
  });

  Project.associate = function(models) {
    Project.belongsTo(models.Student, {
      foreignKey: 'student_id',
      as: 'student',
      onDelete: 'CASCADE',
    });
  };
  return Project;
};
'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Students', {
      _id: {
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      email: {
        type: Sequelize.TEXT,
        allowNull: false,
        unique: true,
      },
      dateOfBirth: {
        type: Sequelize.DATEONLY,
        allowNull: false,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Students');
  },
};
'use strict';

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Projects', {
      project_id: {
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
      },
      student_id: {
        type: Sequelize.UUID,
        references: {
          model: {
            tableName: 'Students',
          },
          key: '_id',
        },
        allowNull: false,
        onDelete: 'CASCADE',
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
        unique: true,
      },
      description: {
        type: Sequelize.TEXT,
        allowNull: true,
      },
      creationDate: {
        type: Sequelize.DATEONLY,
        allowNull: true,
      },
      repoUrl: {
        type: Sequelize.TEXT,
        allowNull: true,
      },
      liveUrl: {
        type: Sequelize.TEXT,
        allowNull: true,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });
  },

  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Projects');
  },
};
node-sequelize-examples=# select * from "Students";
                 _id                  |     name      |          email           | dateOfBirth |           createdAt           |           updatedAt
--------------------------------------+---------------+--------------------------+-------------+-------------------------------+-------------------------------
 2c6db3cb-82c7-4728-a259-23520bd760d0 | Rosalind Mohr | Natasha.Littel@gmail.com | 2020-02-13  | 2020-02-13 12:39:23.508379+00 | 2020-02-13 12:39:23.508379+00
(1 row)

node-sequelize-examples=# select * from "Projects";
              project_id              | name  | description | creationDate | repoUrl | liveUrl |           createdAt           |           updatedAt           |              student_id
--------------------------------------+-------+-------------+--------------+---------+---------+-------------------------------+-------------------------------+--------------------------------------
 b271060c-bd20-48f4-a8a5-65508b99cfbf | nobis |             |              |         |         | 2020-02-13 12:39:23.540054+00 | 2020-02-13 12:39:23.540054+00 | 2c6db3cb-82c7-4728-a259-23520bd760d0
(1 row)
node-sequelize-examples=# \d "Students";
              Table "public.Students"
   Column    |           Type           | Modifiers
-------------+--------------------------+-----------
 _id         | uuid                     | not null
 name        | character varying(255)   | not null
 email       | text                     | not null
 dateOfBirth | date                     | not null
 createdAt   | timestamp with time zone | not null
 updatedAt   | timestamp with time zone | not null
Indexes:
    "Students_pkey" PRIMARY KEY, btree (_id)
    "Students_email_key" UNIQUE CONSTRAINT, btree (email)
Referenced by:
    TABLE ""Projects"" CONSTRAINT "Projects_student_id_fkey" FOREIGN KEY (student_id) REFERENCES "Students"(_id) ON UPDATE CASCADE ON DELETE CASCADE

node-sequelize-examples=# \d "Projects";
               Table "public.Projects"
    Column    |           Type           | Modifiers
--------------+--------------------------+-----------
 project_id   | uuid                     | not null
 name         | character varying(255)   | not null
 description  | text                     |
 creationDate | date                     |
 repoUrl      | text                     |
 liveUrl      | text                     |
 createdAt    | timestamp with time zone | not null
 updatedAt    | timestamp with time zone | not null
 student_id   | uuid                     |
Indexes:
    "Projects_pkey" PRIMARY KEY, btree (project_id)
    "Projects_name_key" UNIQUE CONSTRAINT, btree (name)
Foreign-key constraints:
    "Projects_student_id_fkey" FOREIGN KEY (student_id) REFERENCES "Students"(_id) ON UPDATE CASCADE ON DELETE CASCADE

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign k


Tag : mysql , By : jay
Date : March 29 2020, 07:55 AM

set existing foreign key column to nullable in alter table migration


Tag : php , By : Arnaud Goudsmit
Date : March 29 2020, 07:55 AM
I wish this help you I first created a migration like this: , 1- Delete your foreign key
$table->dropForeign('table1_user_id_foreign');
//If user_id is not unsigned remove unsigned function
$table->integer('user_id')->nullable()->unsigned()->change();   
$table->foreign('user_id')->references('id')->on('users');
Schema::table('table1',function(Blueprint $table){
    //Or disable foreign check with: 
    //Schema::disableForeignKeyConstraints();
    $table->dropForeign('table1_user_id_foreign');
    $table->integer('user_id')->nullable()->unsigned()->change();
    //Remove the following line if disable foreign key
    $table->foreign('user_id')->references('id')->on('users');
});
Related Posts Related QUESTIONS :
  • Why 'activerecord-import' doesn't perform bulk insert?
  • Setting environment variables in ubuntu production server and Rails
  • rails belongs_to optional but check exists if passed
  • How are parameters sent when I use instance variables in form_for in rails
  • Deploying a Rails App to Multiple Servers using Capistrano - Best Practices
  • Rails Model Relationship: Has one but also belongs to many
  • How to override a render to create a custom "render :my_format => argument" in rails 2.3(.5)?
  • What happened to Builder::XmlMarkup in Rails 3?
  • Rails 3 Beta 2, Haml, Nested Layouts and LocalJumpError
  • Rails Layout name inside view
  • split html text in 2 paragraphs
  • Pass variable from Devise controller to custom mailer?
  • How to pass formdata in swagger with require ruby on rails
  • How can i resolve this- rake:aborted! Mysql2::Error: Access denied for user 'root'@'localhost' (using password: NO)
  • random ActionController::InvalidAuthenticityToken in my rails app
  • How to determine which controller has been called from ApplicationController?
  • Parameterize an ActiveRecord #joins method
  • Why the redis returning more values instead of count?
  • Is this ruby(rails) code readable simply?
  • Can I see what SQL an ActiveRecord .save call would generate, without doing the save?
  • Time.current.tap{|t| t.change hour: 10 } is not working in Rails 4.2
  • Write active decorator DRY
  • Creating 2 Models in Controller Action With Transaction - Rails 4
  • How do I display the text with all of the tabs and new lines (\t and \n) in Ruby on Rails?
  • Why my Module is not being loaded in Rails?
  • how to retrieve data from the database using the has_many association
  • Out of ranger error, Type::Integer during rspec test
  • Generate a video from many images using RMagick in RoR
  • Calling an overriden scope from an included concern in the overriding scope
  • ActionController::UnknownFormat on Bugsnag
  • How do I pass a person object into a related Post model object
  • rubocop cannot load such file -- rubocop-rails
  • Malicious Bots waking up heroku free app and using up all dyno hours
  • How to do RSpec of validators?
  • Is there a way to wrap the response of all controller methods in a json object in application_controller.rb?
  • Need to implement #cache! if you want to use Cloudinary::CarrierWave::Storage as a cache storage
  • How to integrate custom bootstrap theme in activeadmin
  • How can I load an STI record using just the base STI class?
  • Getting the .each loop result with the lowest number from json
  • When and where to aggregate or perform calculations on data in RESTful Rails API
  • How do you write a conditional ternary operator inline in Ruby on Rails?
  • Why put require statement at the end of a ruby file?
  • In Rails, is it possible to display an alert without calling redirect_to or render?
  • Convert hash of hash in array of hash
  • Rails 5 tries to save the empty string as nil
  • websocket-driver was not found on deploy
  • Dangerous query method deprecation warning on Rails 5.2.3
  • Using ERB in Markdown with Redcarpet
  • How to create list of unique array items from thousands of records in Rails?
  • Undefined method 'suspend_paypal' for User
  • Any good methods to find Ruby on Rails memory leak?
  • Why does if __FILE__ == $0 not work on Heroku with Rails 5.2?
  • Rails: How to implement login and authentication where i have five different user models in rails?
  • What is the impact of changing rails secret_key_base on production?
  • how to keep heroku dyno worker alive if web dyno goes to sleep?
  • syntax error, unexpected end-of-input, expecting keyword_end. when running rspec of feature file
  • How does form_with know which method to call inside a model?
  • When using activestorage in Rails 6, how do I retain a file when redisplaying a form?
  • How to override table column value with column value from second table if it exist?
  • Comparison of !! operator vs present?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com