在Rails 5中,我想创建一个Author模型的新实例,但在这个过程中我只想从我的User模型中复制属性值(列)的一个子集。
我正在尝试运行以下代码:
user = User.first
Author.create user.attributes.without("id", "token", "secret", "created_at", "updated_at", "active", "email", "encrypted_password", "first_name", "last_name", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip")
User.first方法工作并从表中返回有效用户。但是,Author.create行不起作用。我得到一个NoMethodError:未定义的方法`每个'为nil:NilClass错误。
这是schema.rb文件中的User表:
create_table "users", force: :cascade do |t|
t.string "provider", null: false
t.string "uid", null: false
t.string "name"
t.string "location"
t.string "image_url"
t.string "url"
t.string "token"
t.string "secret"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "active", default: false
t.text "description"
t.string "screen_name"
t.integer "followers"
t.integer "following"
t.integer "statuses"
t.integer "listed"
t.integer "lists"
t.integer "favorites"
t.integer "views", default: 0
t.string "website"
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "first_name", default: "", null: false
t.string "last_name", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.index ["active"], name: "index_users_on_active", using: :btree
t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
t.index ["provider", "uid"], name: "index_users_on_provider_and_uid", unique: true, using: :btree
t.index ["provider"], name: "index_users_on_provider", using: :btree
t.index ["uid"], name: "index_users_on_uid", using: :btree
end
这是我的作者表:
create_table "authors", force: :cascade do |t|
t.string "uid", null: false
t.string "provider", null: false
t.string "name"
t.string "location"
t.string "image_url"
t.string "url"
t.text "description"
t.string "screen_name"
t.integer "followers", default: 0
t.integer "following", default: 0
t.integer "statuses", default: 0
t.integer "listed", default: 0
t.integer "lists", default: 0
t.integer "favorites", default: 0
t.integer "views", default: 0
t.string "website"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["provider"], name: "index_authors_on_provider", using: :btree
t.index ["uid", "provider"], name: "index_authors_on_uid_and_provider", unique: true, using: :btree
t.index ["uid"], name: "index_authors_on_uid", using: :btree
end
如您所见,新的Author表具有许多与User表相同的列/属性,但我只想在创建新的Author对象时复制User属性的一个子集(列和值)。
也许user.attributes.without方法不正确?