Add nullable foreign key in Rails

后端 未结 3 1056
孤街浪徒
孤街浪徒 2020-12-13 17:40

Referencing to Rails 4.2 add_foreign_key support:

    # add a foreign key to `articles.author_id` referencing `authors.id`
    add_foreign_key :articles, :au         


        
3条回答
  •  误落风尘
    2020-12-13 17:53

    Note that in Rails 5 and in Rails 6 you may need to mark the corresponding association as optional if it's 1:n (belongs_to), as the default was changed:

    belongs_to :author, optional: true

    This is the corresponding Changeset.

    To use the old behavior across your application, you can also set:

    Rails.application.config.active_record.belongs_to_required_by_default = false
    

    in config/initializers/new_framework_defaults.rb

    The error you will usually see is:

    ActiveRecord::RecordInvalid: Validation failed: Class must exist
        from /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/validations.rb:78:in `raise_validation_error'
    

    You may also need to update any migration: change null: false to true and run rake db:redo if it had already run.

提交回复
热议问题