Rails 5 belongs_to默认行为

时间:2016-12-28 17:37:46

标签: ruby-on-rails activerecord rails-activerecord

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

此测试因当前的rails master而失败。 我认为它应该成功,因为默认情况下需要belongs_to来自Rails 5。

这是预期的行为吗?

1 个答案:

答案 0 :(得分:4)

您是对的, Rails 5 中默认需要belongs_to。在您的示例中,您没有运行 Rails 5 应用,只是使用了ActiveRecord

Rails 5中默认需要

belongs_to,因为当您生成新的Rails 5应用程序时,会得到一个文件config/initializers/new_framework_defaults.rb,其中包含以下行:

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

要在您的示例中获得类似的结果,您还必须为ActiveRecord设置此配置选项(默认情况下,它未设置,这意味着它是nil,也就是虚假值:

# 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 :)

现在,如果您运行测试,它们将通过。

有关详情,请参阅this pull request