ActiveRecord NoMethodError:nil的未定义方法`association':NilClass

时间:2018-03-04 17:30:44

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

使用Rails 5.1.4,在使用#find更改has_many以预加载#includes关联后:

Website.includes(:configured_checks).find(params[:id])

抛出异常:

NoMethodError: undefined method `association' for nil:NilClass

1 个答案:

答案 0 :(得分:2)

idx_id需要具有相同的类型

此问题暴露了重命名has_many关系所有者的错误。重命名表后,关联上的t.belongs_to列的类型不再与其引用的表匹配,从而导致NoMethodError: undefined method 'association' for nil:NilClass

架构不正确:

# Website id here is a UUID:
create_table "websites", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t|
end

# The foreign_key became a binint rather than uuid:
create_table "configured_checks", force: :cascade do |t|
  t.bigint "website_id"
end

迁移后修正架构:

# Website id here is a UUID:
create_table "websites", id: :uuid, default: -> { "uuid_generate_v4()" }, force: :cascade do |t|
end

# The website_id is now a uuid:
create_table "configured_checks", force: :cascade do |t|
  t.uuid "website_id"
end