Question: Rails 5 belongs_to default behavior

Question

Rails 5 belongs_to default behavior

Answers 1
Added at 2016-12-28 18:12
Tags
Question
begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"
  gem "rails", github: "rails/rails"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end

  create_table :comments, force: true do |t|
    t.integer :post_id
  end
end

class Post < ActiveRecord::Base
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

class BugTest < ActiveSupport::TestCase
  def test_association_stuff
    post = Post.create!

    comment = Comment.create
    assert_not_empty comment.errors.full_messages
  end
end

This test fails with current rails master. I think it should succeed since belongs_to required by default from Rails 5.

Is this expected behavior?

Answers to

Rails 5 belongs_to default behavior

nr: #1 dodano: 2016-12-28 19:12

You are right, belongs_to is required by default in Rails 5. In your example, you are not running a Rails 5 app, you are just using ActiveRecord.

belongs_to is required by default in Rails 5 because when you generate a new Rails 5 app, you get a file config/initializers/new_framework_defaults.rb which has the following line:

# Require `belongs_to` associations by default. Previous versions had false.
Rails.application.config.active_record.belongs_to_required_by_default = true

To achieve similar results in your example, you have to set this config option for ActiveRecord as well (by default it's not set, which means it's nil, aka falsy value):

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.belongs_to_required_by_default = true # <-- This line :)

Now if you run your tests, they will pass.

For more info, reference this pull request.

Source Show
◀ Wstecz