ruby-on-rails - 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
我是否还需要在事件表中添加外键?我可以看到我没有做我认为是错误的事情......
解决方案
应将外键添加到您从中进行引用的表中。在这种情况下,您正在从事件中引用用户。所以 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
就足够了
推荐阅读
- r - 如何减少 R 中的级别数?
- java - 比较两个数组以仅检索 JSP 中的完全匹配,同时保留下拉菜单中的显示顺序
- spring - 如何拦截 Spring 校长?
- c++ - "new (ptr) mystruct;" 是什么意思?为没有功能的结构做什么?
- amazon-web-services - 通过 CloudFormation 修改现有 AWS Config 交付通道
- php - API 平台,在 MongoDB 中使用 EmbedOne 发布对象
- fortran - Fortran 无穷大检查显示无穷大,但值不是
- amazon-web-services - 防止 AWS Autoscalingroup 在通过 Cloudformation 更新期间启动超过最大大小的实例
- python - 在光栅中链接虚拟文件系统驱动程序
- azure - Azure 数据工厂:访问驻留在虚拟网络中的 Web 服务