1
發生的事情我有題目列表(父)和主題(孩子)模型未知屬性錯誤父ID,只有在測試
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並在其下創建一個Topic:
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.
但是當我在我的導軌控制檯中嘗試相同的序列時,它工作得很好。
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
>>
每一個類似的問題,我已經在這裏發現了不正確的首字母大寫,snake_case,或複數/單名交易。我想我已經在這裏做了所有正確的事情。我錯過了什麼?
您的測試數據庫配置是否正確?你能粘貼錯誤的完整堆棧跟蹤嗎? –