当我为数据库添加种子时,出现以下错误:Post的未知属性'user'。
我的模式如下:
create_table "posts", force: :cascade do |t|
t.string "body"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.integer "collection_id"
t.index ["collection_id"], name: "index_posts_on_collection_id"
t.index ["user_id"], name: "index_posts_on_user_id"
end
我的seed.rb文件如下:
require 'faker'
10.times do |user|
User.create!(
name: Faker::Name.name,
birthday: '2019-09-04',
skin_type: 'Dry',
email: Faker::Internet.email,
password:Faker::Internet.password
)
end
users = User.all
puts "Users seeded"
50.times do
Post.create!(
user: users.sample,
body: Faker::Lorem.paragraphs
)
end
我创建的Post迁移文件如下:
class CreatePosts < ActiveRecord::Migration[5.2]
def change
create_table :posts do |t|
t.string :body
t.timestamps
end
end
end
在我的seed.rb文件中,创建Post.create!无法访问用户属性。这是因为用户属性未包含在CreatePosts迁移文件中吗?这应该没关系,因为在架构中,post和user_id已连接?
答案 0 :(得分:1)
根据您对评论的讨论,您需要在帖子模型中添加用户关联:
class Post < ApplicationRecord
belongs_to :user
end