父ID的未知属性错误,仅在测试中发生

时间:2016-11-16 21:30:58

标签: ruby-on-rails

我有TopicList(父)和Topic(子)模型

class TopicList < ApplicationRecord
    has_many :topics
    validates :name, presence: true , uniqueness: { case_sensitive: false }
end

class Topic < ApplicationRecord
  belongs_to :topic_list
  validates :topic_list_id, presence: true
  validates :name, presence: true, uniqueness: { case_sensitive: false }
end

schema.rb包括:

ActiveRecord::Schema.define(version: 20161116031922) do

  create_table "topic_lists", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["name"], name: "index_topic_lists_on_name", unique: true
  end

  create_table "topics", force: :cascade do |t|
    t.string   "name"
    t.string   "source"
    t.integer  "position"
    t.integer  "topic_list_id"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
    t.index ["name"], name: "index_topics_on_name", unique: true
    t.index ["position"], name: "index_topics_on_position"
    t.index ["topic_list_id"], name: "index_topics_on_topic_list_id"
  end

我的topic_test.rb首先创建一个新的TopicList并在其下构建一个主题:

require 'test_helper'

class TopicTest < ActiveSupport::TestCase
  def setup
    @topic_list = TopicList.new(name: "Vocab")
    @topic_list.save
    @topic = @topic_list.topics.build(name: "Topic 1")
  end

  test "should be valid" do
    assert @topic.valid?
  end
end

每当我运行此测试时,我都会收到错误:

ActiveModel::UnknownAttributeError: unknown attribute 'topic_list_id' for Topic.

但是当我在rails控制台中尝试相同的序列时,它可以正常工作。

Loading development environment (Rails 5.0.0.1)
>> list = TopicList.new(name: "List 1")
=> #<TopicList id: nil, name: "List 1", created_at: nil, updated_at: nil>
>> list.save
   (0.1ms)  begin transaction
  TopicList Exists (0.3ms)  SELECT  1 AS one FROM "topic_lists" WHERE LOWER("topic_lists"."name") = LOWER(?) LIMIT ?  [["name", "List 1"], ["LIMIT", 1]]
  SQL (0.3ms)  INSERT INTO "topic_lists" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "List 1"], ["created_at", 2016-11-16 21:23:33 UTC], ["updated_at", 2016-11-16 21:23:33 UTC]]
   (11.3ms)  commit transaction
=> true
>> topic = list.topics.build(name: "Topic #1")
=> #<Topic id: nil, name: "Topic #1", source: nil, position: nil, topic_list_id: 3, created_at: nil, updated_at: nil>
>> topic.valid?
  Topic Exists (0.2ms)  SELECT  1 AS one FROM "topics" WHERE LOWER("topics"."name") = LOWER(?) LIMIT ?  [["name", "Topic #1"], ["LIMIT", 1]]
=> true
>> 

我在这里找到的每个类似问题都涉及不正确的CamelCase,snake_case或复数/单个名称。我想我已经在这里完成了所有这些。我错过了什么?

1 个答案:

答案 0 :(得分:0)

我跑了<script src="scripts/vendors/jquery.js"></script> <script src="scripts/vendors/bootstrap.js"></script> <script src="scripts/vendors/angular.js"></script> <script src="scripts/vendors/angular-route.js"></script> ,然后清理了它。不知道为什么有时需要这样做而不是其他人。