未知属性:USER_ID [英] unknown attribute: user_id

查看:117
本文介绍了未知属性:USER_ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误未知属性:USER_ID durring执行current_user.stories.build的

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

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

它不包含USER_ID字段。任何想法?

It doesn't contain 'user_id' field. Any ideas?

推荐答案

,你需要在你的的故事定义了一个 USER_ID 列Kulbir是正确的表,但并没有解释这样做的方式。

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.

正确的方法进行改变是创建一个新的迁移。按照惯例,应该叫 add_user_id_to_stories 键,将创建如下(假设你使用的Rails 3 +):

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

作为您关注的有关协会命名,你是Rails的惯例一边时,你其实可以跳过很多额外的规范。在用户模式,您可以只指定的has_many:故事故事模型指定 belongs_to的:用户。 Rails会假设你已经指定了相同的类名和外键。

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.

这篇关于未知属性:USER_ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆