【问题标题】:Associations within Rails Engine not workingRails 引擎中的关联不起作用
【发布时间】:2021-01-18 21:21:12
【问题描述】:

我正在构建我的第一个 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

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

【问题讨论】:

  • 我无法重现第一个问题,尽管您的示例存在一些问题,我无法判断它们是您的代码/问题的一部分还是您的示例的问题(例如,默认情况下,文章表会是blorgh_articles 而不是blorgh_article)。然而,第二个问题是 Rails 假定 has_many 关系上的外键是 classname_id(所以,author_id)。使用命名空间模型时,您只需要在has_many 端以及belongs_to 端指定foreign_key
  • 谢谢@rmlockerd!实际上已经是这样了:)我只需要正确地添加外键,第二个问题就奏效了。首先,我现在发现应该做一个更复杂的验证。正如我现在所知,我可以从那里出发。对于blorgh_article 问题,这是由于我的示例,抱歉...我在问题中对其进行了编辑。随意将您的评论作为答案,所以我可以标记它:)

标签: ruby-on-rails activerecord associations rails-engines


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多