ruby-on-rails - Rails 引擎中的关联不起作用
问题描述
我正在构建我的第一个 Rails 引擎,并且已经对定义两个模型之间的关联感到非常困惑。为方便起见,假设引擎的名称是Blorg,有两个模型Article和Author。
blorgh/article.rb
module Blorgh
class Article < ApplicationRecord
belongs_to :author, class_name: 'Blorg::Author',
foreign_key: 'blorg_author_id', optional: true
blorgh/author.rb
module Blorgh
class Author < ApplicationRecord
has_many :articles, class_name: 'Blorg::Article'
图式
create_table "blorgh_authors", force: :cascade do |t|
t.string "name"
t.boolean "inactive", default: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
create_table "blorgh_articles", force: :cascade do |t|
t.string "title"
t.bigint "blorgh_author_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["blorgh_author_id"], name: "index_blorgh_article_on_author_id"
如果我尝试通过 rails c 创建文章或计算作者的文章,我会收到以下错误:
article = Blorgh::Article.new(title: 'New Article')
article.save # expect true
# ==> NoMethodError: private method `attribute' called for #<Blorgh::Article:0x00007fdc3fad4d50>
author = Blorgh::Author.create # worked
author.articles.count # expect 0
# ==> ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column blorgh_articles.author_id does not exist
有谁知道我如何正确实现这些引擎内关联?
解决方案
第二个错误(“列 blorgh_articles.author_id 不存在”)是因为 Rails 假定has_many
关系上的外键是类名 _id,author_id
在您的示例中。您正确设置了belongs_to
侧的外键,但您需要在关系的两侧指定。所以:
module Blorgh
class Author < ApplicationRecord
has_many :articles, class_name: 'Blorg::Article', foreign_key: 'blorg_author_id'
...
推荐阅读
- python-3.x - 如何使用熊猫清理坐标系的 CSV 文件?
- java - 无法从 spring boot .jar 读取文件
- html - 在 sass 中定义字体真棒内容时不显示
- sql - Db2/sql:使用连接选择和更新最旧的条目
- python - 为列表的总和获取大量小数位。所有列表项的小数点后均不超过 2 位。我究竟做错了什么?
- spring-boot - 在 Spring Boot 中挂钩以插入自己的 RabbitMQ 客户端?
- c++ - .CSV 文件的输出问题
- node.js - Next.js 在 Ubuntu EAGAIN 上构建失败
- java - 将 CSS 表添加到 Intellij JavaFX 项目
- css - material-ui中的设备宽高