Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign key is allowed to be NULL?

I have a table which MUST have a case_id that is valid and exists, and the record should not be created unless it exists. I should not be able to pass a NULL case_id.

It looks like:

# == Schema Information
#
# Table name: medical_intervention_expert_answers
#
#  id                      :integer          not null, primary key
#  case_id                 :integer
#  problem_id              :integer
#  medical_intervention_id :integer
#  created_at              :datetime
#  updated_at              :datetime
#  pti                     :boolean
#

class MedicalInterventionExpertAnswer < ActiveRecord::Base
    belongs_to :case
    belongs_to :problem
    belongs_to :medical_intervention

    def self.create_from_data(case_id, problem_id, medical_intervention_id, is_pti)
        answer = self.create(case_id: case_id, problem_id: problem_id, medical_intervention_id: medical_intervention_id, 
            pti: is_pti)

        return answer
    end
end

If I pass in a case_id that is null or pass in a case_id that does not exist, the 'answer' variable should be nil and the database should be unmodified.

What must I do to have this sort of relation?

like image 965
jmasterx Avatar asked Sep 28 '22 21:09

jmasterx


1 Answers

For add foreign key, you add first the name of table (not the model name), this as first parameter, and as second parameter the name of foreign table(not the model name). The table as first parameter should have a column with a name specific as follow: name_foreign_model_id. Example: Foreign model

class CreateGrades < ActiveRecord::Migration
  def change
    create_table :grades do |t|
      t.string :name, limit: 20
      t.integer :level, limit: 2
      t.string :next, limit: 20

      t.timestamps null: false
    end
  end
end

And,

class CreateGoals < ActiveRecord::Migration
  def change
    create_table :goals do |t|
      t.integer :dimension, limit: 2, null: false
    **t.integer :grade_id, null: false**
      t.string :description, limit: 1024, null: false

      t.timestamps null: false
    end
    **add_foreign_key :goals, :grades**
  end
end

Also you can add foreign key in a separate migration.

With this, not should accept null foreign key.

like image 84
cristiancvanega Avatar answered Oct 05 '22 06:10

cristiancvanega