Roberto Balejík
Roberto Balejík

Reputation: 41

rails models: can be foreign key null?

I have an event table and a place table. Some events belongs to some places, while others don't. So I decided to create another table: placed_event = events which belongs to place. My question is: should I keep it this way or only have the placed_event table and delete events table, so that some placed_events will have foreign key null - i.e. would not belong to any place?

Upvotes: 0

Views: 238

Answers (2)

Ryan K
Ryan K

Reputation: 4053

If a place has_many events and events belongs_to a place, you can always leave place_id empty(nil). It isn't mandatory for all (or any) associations to be present (unless you explicitly have a validation). You should, of course, check for this in your code so you don't try accessing data from an association that doesn't exist (i.e. calling @event.place.name when place is nil).

Upvotes: 0

Matt
Matt

Reputation: 311

The answer is "it depends."

If events can be in 0 or 1 places, then having an events table with a foreign key to a places table will work fine; as Mohammad said in his comment, if the place_id is null, the event just doesn't have a place.

If events can be spread across more than one place, like a concert with many stages, that's when having a join table would make sense.

Hope that helps.

Upvotes: 1

Related Questions