Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails - set up a null foreign key

How do I set a foreign key null? because I want to relate two tables, user and team, but it is not mandatory for a user to have a team.

rails g scaffold Time name: string user: references

like image 636
taynan Avatar asked Aug 31 '25 03:08

taynan


1 Answers

Rails level ( model validation )

In Rails 4.x , when defining a references, the associated record for belongs_to is optional. From Rails 5.x, this association is required.

In Rails 4, to make associated record required, you will do

class Photo
  belongs_to :user, required: true
end

In Rails 5, to make associated record optional, you will do

class Photo
  belongs_to :user, optional: true
end

DB level

You need to make sure that your migration does not have constraint null: false. You should check migration to make sure it looks sth like below

create_table :photos do |t|
   t.references :user, null: true, foreign_key: true
end
like image 126
quyetdc Avatar answered Sep 02 '25 18:09

quyetdc