Search code examples
ruby-on-railsdatabaseschemarails-migrations

Getting an Unknown Attribute error when seeding database


When I seed my database, I get this error: unknown attribute 'user' for Post.

My schema looks like this:

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

My seeds.rb file looks like this:

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

My creating Post migration file looks like this:

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :body
      t.timestamps
    end
  end
end

In my seeds.rb file, Post.create! cannot access the user attribute. Is this because the user attribute is not included in the CreatePosts migration file? Shouldn't this not matter since within the schema, posts and user_id are connected?


Solution

  • Based on your discussion on the comments, you need to add user association in the post model:

    class Post < ApplicationRecord
      belongs_to :user
    end