Search code examples
ruby-on-railsrails-activerecordhas-manybelongs-to

Is there a way in rails to make a model optionally belong to another model?


I am building a rails exercise app that has both exercises and routines. I want each routine to be composed of several exercises (has_many :exercises), but an exercise doesn't necessarily have to belong to a routine. Is there a way to do that?


Solution

  • Reading the guides is always a good start. This works from Rails 5 onwards.

    belongs_to :routine, optional: true