unknown attribute: user_id

activerecord, ruby, ruby-on-rails

Solution

Kulbir is correct that you need to define a `user_id` column in your `stories` table, but doesn't explain the way to do that.

The correct way to make that change is to create a new migration. By convention, it should be called `add_user_id_to_stories` and would be created as follows (assuming you're using Rails 3+):

rails generate migration add_user_id_to_stories

If you run that, it should actually generate a migration that already contains the change you need to make, which should be something like:

add_column :stories, :user_id, :integer

As an aside when you're following the Rails conventions concerning association naming, which you are, you can actually skip a lot of the extra specification. In the `User` model, you can specify just `has_many :stories` and in the `Story` model specify `belongs_to :user`. Rails will assume the same class names and foreign keys you've specified.

Problem

I'm getting the error unknown attribute: user_id durring execution of current_user.stories.build ``` class User < ActiveRecord::Base has_many :stories, class_name: 'Story', foreign_key: 'user_id', dependent: :destroy ... class Story < ActiveRecord::Base belongs_to :user, class_name: 'User', foreign_key: 'user_id' ... ``` schema.rb ``` create_table "stories", :force => true do |t| t.string "responsible" t.string "descr" t.string "state" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end create_table "users", :force => true do |t| t.string "email" t.string "password_digest" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "name" end ``` It doesn't contain 'user_id' field. Any ideas?

Original source