Add nullable foreign key in Rails
There is nothing in the guide that implies add_foreign_key
would make the corresponding foreign field "NOT NULL" or required. add_foreign_key
simply adds a foreign key constraint whether the field is required or not (in your case author_id
in articles
).
Did you get an error when you tried this in your migration?
Here's the SQL that it would generate:
ALTER TABLE "articles" ADD CONSTRAINT articles_author_id_fk FOREIGN KEY ("author_id") REFERENCES "authors" ("id")
SO, if in your original migration of articles
, author_id
is null, then you can have foreign key that's nullable.
Ruby on rails - set up a null foreign key
It's allowed to be null on db level. Within Time models add optional option, like - belongs_to :user, optional: true
Check related docs here
rails 6 foreign key can't be null
Migrations are not a declaration of current db structure, they are changes that when combined - produce it. For combined structure rails have db/schema.rb
(or schema.sql
for more complex scenarios)
If the column is null: false
then it must have been changed by some later migration (or directly in db, if so - db structure may be out of sync between development and production). If you want it again to be null: true
- add another migration that will change that. But first I'd figure out why it ended up in current state, may be there's a reason.
change_column :carts, :user_id, :bigint, null:true
Foreign key is allowed to be NULL?
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.
Ruby on Rails foreign key field cannot be null
You can make the assignments conditional on whether there's already a value...
before_validation do
self.banned = false if banned.nil?
self.role ||= Role.find_by(title: 'User')
end
Or you can do it only on create....
before_validation do
if new_record?
self.banned = false
self.role = Role.find_by(title: 'User')
end
end
But frankly the way I normally see initial defaults set is in the create
method of the controller
def create
@user = User.assign_attributes(user_params)
@user.banned = false
@user.role = Role.find_by(title: 'User')
if @user.save
# ...
Rails foreign key optional don't work
You don't need foreign_key: true
on the t.refrences
lines. They'll force referential integrity tests.
Roll back, then change the migration to...
t.references :deck
t.references :game
Alternatively you can just create the integer fields and bypass the database integrieites
t.integer :deck_id
t.integer :game_id
User_ID foreign key NULL in Rails
Not sure , may be because you didn't run it properly. Please recheck all this below conditions.
- user_id must be in website table . To add migration you should run
rails g migration AddUserIdToZombies user_id:integer
and thenrake db:migrate
- To ensure the user_id must be there with websites table,put validation.
- To assign user_id automatically,you should do something like
u = User.find 1
u.websites.create(attr: 'value')
FYI :Rails dont use foreign key concept. It means that they dont put link in database. They just provide abstract way of linking models.
Related Topics
How to Check to See If My Array Includes an Object
How to Validate Exits and Aborts in Rspec
Using a String as a Variable at Run Time
Iterate Over a Deeply Nested Level of Hashes in Ruby
How to Detect Certain Unicode Characters in a String in Ruby
Why Is _File_ Uppercase and _Dir_ Lowercase
Strange Inability to Require Config/Boot After Upgrading to Ruby 1.9.2
Flattening Nested Hash to a Single Hash with Ruby/Rails
How to Install the Ruby Ri Documentation
How to Install Jekyll on Osx 10.11
Installing Cocoapods: No Response
How to Suppress Rails Console/Irb Outputs
Rvm Ruby 1.9.1 Install Can't Locate Zlib But Its Runtime and Dev Library Are There
A Copy of Xxx Has Been Removed from the Module Tree But Is Still Active
How to Merge Array of Hashes to Get Hash of Arrays of Values