Reputation: 131
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
Upvotes: 4
Views: 5278
Reputation: 1585
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
Upvotes: 5
Reputation: 691
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
Upvotes: 5
Reputation: 1227
When you're designing your tables it's not advisable to put data which is not related to the parent.
For example: User can have multiple photos
user table
id name
photos table
id url user_id
if you're going to store photos without user_id then those photos will not be retrieved when you want to access photos of a particular user. That's why rails doesn't allow you to store records if you've defined a column as references
.
you can refer the issue here DHH github (rails).
In the association add optional: true
to achieve this functionality.
Upvotes: 0