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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With