首页 > 解决方案 > Rails 帮助 - 事件的未知属性“creator_id”

问题描述

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
      
  has_many :events, foreign_key: :creator_id, class_name: "Event"
end

class Event < ApplicationRecord
  belongs_to :creator, class_name: "User", foreign_key: :creator_id
end

当我转到事件/新路线时,我收到此错误:unknown attribute 'creator_id' for Event.我已经完成了数据库迁移,我已经添加了before_action's.

  def new
    @event = current_user.events.build(event_params)
  end

有任何想法吗?

更新:

 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20210610064055  Create events
   up     20210610070312  Devise create users
   up     20210612072338  Add body title to event
   up     20210612091329  Add foreign key

**根据评论部分的要求进行进一步更新。**

迁移文件:

class AddForeignKey < ActiveRecord::Migration[6.1]
  def change
    add_column :users, :creator_id, :integer
  end
end

数据库模式文件:

 create_table "events", force: :cascade do |t|
    t.date "date"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "title"
    t.text "body"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "creator_id"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

我是否还需要在事件表中添加外键?我可以看到我没有做我认为是错误的事情......

标签: ruby-on-rails

解决方案


应将外键添加到您从中进行引用的表中。在这种情况下,您正在从事件中引用用户。所以 creator_id 必须添加到事件中。它引用了一个特定的 users.id 值。因此,您需要从中删除它们的外键users并将其添加到其中events

class AddForeignKey < ActiveRecord::Migration[6.1]
  def change
    add_column :events, :creator_id, :integer
  end
end

此外,无需在 rails 模型中专门指定外键。导轨指南状态:

按照惯例,Rails 猜测该模型上用于保存外键的列是关联名称加上后缀 _id。:foreign_key 选项允许您直接设置外键的名称:

所以

class Event < ApplicationRecord
  belongs_to :creator, class_name: "User"
end

就足够了


推荐阅读