TIMBERings
TIMBERings

Reputation: 768

ActiveModel::MissingAttributeError: can't write unknown attribute `user_id`?

I've got a schema with leagues

  create_table "leagues", force: :cascade do |t|
    t.string   "name",                           null: false
    t.date     "start_date",                     null: false
    t.date     "end_date"
    t.string   "day"
    t.string   "start_time",                     null: false
    t.integer  "practice_length",                null: false
    t.integer  "alley_id",                       null: false
    t.integer  "frequency",                      null: false
    t.integer  "scratch",          default: 220
    t.integer  "handicap_percent", default: 80
    t.integer  "handicap_round",   default: 0
    t.integer  "occurrences",                    null: false
    t.integer  "user_id",                        null: false
    t.datetime "created_at",                     null: false
    t.datetime "updated_at",                     null: false
  end

and models

class Alley < ActiveRecord::Base
  belongs_to :address
  has_many :leagues
end

class User < ActiveRecord::Base
  has_many :leagues
end

class League < ActiveRecord::Base
  belongs_to :alley
  belongs_to :user
  has_many :teams
end

and factory

factory :league do
  name Faker::Company.name
  start_date start_date
  end_date end_date
  day Date.today.day
  start_time '7:00pm'
  practice_length 10
  frequency 1
  occurrences weeks

  association :alley, factory: :alley
  association :user, factory: :user
end

factory :user do
  email '[email protected]'
  password 'Test1234'
  password_confirmation { 'Test1234' }
end

factory :alley do
  name Faker::Company.name
  association :address, factory: :address
end

When I try to create a league, I get an error

ActiveModel::MissingAttributeError: can't write unknown attribute user_id

It's set up exactly like alley, and alley works. A league should be assigned to an alley and assigned to a user. An alley can have many leagues and a user can have many leagues. Frankly, I'm too tired to figure out why this isn't working currently.

Upvotes: 2

Views: 4010

Answers (2)

Cody Elhard
Cody Elhard

Reputation: 675

In my case my tests were failing. Thanks to @TIMBERings answers I was able to narrow it down.

If you create a migration without an index, migrate forward, add the index (or reference) to the migration file, migrate or rollback, migrate forward again, you're messed up

To Fix my failing RSpec tests I ran the following and reran the tests and it passed.

rails db:reset RAILS_ENV=test

You could also simply run

rails db:reset

Upvotes: 0

TIMBERings
TIMBERings

Reputation: 768

I had been modifying migrations (as I'm getting the initial dataset up), I migrated down, then up. That what got me where I was. I had to drop the database and then run setup. Something must have been stale.

Upvotes: 4

Related Questions