首页 > 解决方案 > Rails 引擎中的关联不起作用

问题描述

我正在构建我的第一个 Rails 引擎,并且已经对定义两个模型之间的关联感到非常困惑。为方便起见,假设引擎的名称是Blorg,有两个模型ArticleAuthor

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

有谁知道我如何正确实现这些引擎内关联?

标签: ruby-on-railsactiverecordassociationsrails-engines

解决方案


第二个错误(“列 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'
...

推荐阅读