Best practice about empty belongs_to association

后端 未结 2 1013
情书的邮戳
情书的邮戳 2021-01-30 19:41

Imagine the following situation:

I have a dog model and a house model. A dog can belong to a house, and a house can have many dogs, so:

相关标签:
2条回答
  • 2021-01-30 20:14

    Be careful with this in Rails 5...

    #belongs_to is required by default

    From now on every Rails application will have a new configuration option config.active_record.belongs_to_required_by_default = true, it will trigger a validation error when trying to save a model where belongs_to associations are not present.

    config.active_record.belongs_to_required_by_default can be changed to false and with this keep old Rails behavior or we can disable this validation on each belongs_to definition, just passing an additional option optional: true as follows:

    class Book < ActiveRecord::Base
      belongs_to :author, optional: true
    end
    

    from: https://sipsandbits.com/2015/09/21/whats-new-in-rails-5/#belongs_toisrequiredbydefault

    0 讨论(0)
  • 2021-01-30 20:15

    I think it is absolutely normal approach.

    You can just leave house_id with null value in database for the models which don't belong to other.

    0 讨论(0)
提交回复
热议问题