unknown attribute: user_id

假如想象 提交于 2019-12-21 07:21:49

问题


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?


回答1:


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.




回答2:


You should have a user_id field in your stories table like below to define the association in your models.

create_table "stories", :force => true do |t|
    t.integer  "user_id"
    t.string   "responsible"
    t.string   "descr"
    t.string   "state"
    t.datetime "created_at",  :null => false
    t.datetime "updated_at",  :null => false
  end
  ...
end

Edit

Check Emily's answer for detailed explanation.




回答3:


you should use the new syntax and pass the fieldtype as symbol

add_column :stories, :user_id, :integer


来源:https://stackoverflow.com/questions/11529405/unknown-attribute-user-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!