播种数据时的ActiveRecord :: unknownAttributeError

时间:2016-08-22 07:30:06

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

当我尝试为我的应用播种时,会弹出此错误。

enter image description here

链接到我的repo

我所做的是: - 创建一个rails应用程序 - 模式中描述的创建的四个模型

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

  create_table "profiles", force: :cascade do |t|
    t.string   "gender"
    t.integer  "birth_year"
    t.string   "first_name"
    t.string   "last_name"
    t.integer  "User_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "todo_items", force: :cascade do |t|
    t.date     "due_date"
    t.string   "title"
    t.text     "description"
    t.boolean  "completed",   default: false
    t.integer  "TodoList_id"
    t.datetime "created_at",                  null: false
    t.datetime "updated_at",                  null: false
  end

  add_index "todo_items", ["TodoList_id"], name: "index_todo_items_on_TodoList_id"

  create_table "todo_lists", force: :cascade do |t|
    t.string   "list_name"
    t.date     "list_due_date"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
    t.integer  "User_id"
  end

  add_index "todo_lists", ["User_id"], name: "index_todo_lists_on_User_id"

  create_table "users", force: :cascade do |t|
    t.string   "username"
    t.string   "password_digest"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

end

我在模型文件

中描述的四个模型之间有一些关系
class User < ActiveRecord::Base
    has_one :profile , dependent: :destroy
    has_many :todo_lists
    has_many :todo_items,through: :todo_lists,source: :todo_items
end

class Profile < ActiveRecord::Base
    belongs_to :user
end

class TodoList < ActiveRecord::Base
    belongs_to :user
    has_many :todo_items , dependent: :destroy
end

class TodoItem < ActiveRecord::Base
  belongs_to :todo_list
end

当我在seed.rb文件中添加一些数据时,错误开始出现,如图所示

User.destroy_all

User.create! [
    {username: "Fiorina" , password_digest: "123"},
    {username: "Trump"   , password_digest: "456"},
    {username: "Carson"  , password_digest: "789"},
    {username: "Clinton" , password_digest: "abc"},     
]
User.find_by!(username: "Fiorina").create_profile(first_name: "Carly"  , last_name: "Fiorina" )
User.find_by!(username: "Trump"  ).create_profile(first_name: "Donald" , last_name: "Trump"   )
User.find_by!(username: "Carson" ).create_profile(first_name: "Ben"    , last_name: "Carson"  )
User.find_by!(username: "Clinton").create_profile(first_name: "Hillary", last_name: "Clinton" ) 

任何人都可以向我解释这个错误意味着什么,或者我应该做些什么?

1 个答案:

答案 0 :(得分:0)

问题在于profiles表中的列名。它的User_id但实际应该是user_id(约定优于配置)

您可以通过重命名列来解决此问题(profilestodo_lists

rails g migration rename_user_id

这将在db/migrate文件夹中生成新的迁移文件。通过将以下内容添加到change方法来编辑迁移文件。

rename_column :profiles, :User_id, :user_id

您还希望重命名User_id表中的todo_lists列,例如

rename_column :todo_lists, :User_id, :user_id