Rails引擎中的关联不工作



我正在构建我的第一个Rails引擎,并且已经在定义两个模型之间的关联时感到非常困惑。为方便起见,假设引擎的名称为blog,有两个模型Article作者和.

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'
<<p>模式/strong>
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

有人知道我如何才能正确实现这些引擎内的关联吗?

第二个错误("column blorgh_articles.)author_id不存在")是因为Rails假设has_many关系上的外键是classname_id,在您的示例中是author_id。您在belongs_to一侧正确地设置了外键,但是您需要在关系的两侧都指定。所以:

module Blorgh
class Author < ApplicationRecord
has_many :articles, class_name: 'Blorg::Article', foreign_key: 'blorg_author_id'
...

最新更新