【问题标题】:RoRails~5: associations with custom db-field namesRoRails~5:与自定义数据库字段名称的关联
【发布时间】:2019-02-01 19:19:53
【问题描述】:

这个问题被讨论了很多次,但是我遇到了一个我找不到答案的问题。

我正在构建一个登录系统,其中一个 Member(:class) “保释”一个新成员。在内部,他们分别被称为“成员”和“候选人”。在成员接受保释之前,BailRequest(:class) 会列在相应的表中。

根据 rails 指南,告诉 rails 所引用的类的正确方法是

class BailRequest < ApplicationRecord
  belongs_to :candidate, class_name: "Member"
  belongs_to :member
end

其中 class_name: "Member" 应该告诉 rails BailRequest.candidate 属于 class: Member。同样的方法在成员类中完美运行

class Member < ApplicationRecord
  belongs_to :bail, class_name: "Member", optional: true
  has_many :associates, class_name: "Member", foreign_key: "bail_id"
end

但是,这一次我想将 BailRequest 保存到数据库时,我得到一个 ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.candidates。

看起来 ActiveRecord 在这里需要一个名为“candidates”的表。我错过了什么?

$ rails -v
Rails 5.2.1

[$ ruby -v
ruby 2.3.1p112 (2016-04-26) [i386-linux-gnu]]

迁移后的 schema.rb 显示如下

  create_table "bail_requests", force: :cascade do |t|
      t.integer "candidate_id"
      t.integer "member_id"
      t.string "message", limit: 100
      t.boolean "accepted"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.index ["candidate_id"], name: "index_bail_requests_on_candidate_id", unique: true
      t.index ["member_id"], name: "index_bail_requests_on_member_id"
  end

  create_table "members", force: :cascade do |t|
    t.string "email", limit: 50, null: false
    t.string "password_digest", null: false
    t.integer "bail_id"
    t.string "username", limit: 50
    t.string "first_name", limit: 50
    t.string "last_name", limit: 50
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_members_on_email", unique: true
    t.index ["username"], name: "index_members_on_username", unique: true
  end

逻辑:

  1. 当成员 m 注册时,m 必须按名称引用成员 n。 m.bail 等于 nil/null 并且创建了一个 BailRequest br br.member = n 和 br.candidate = m
  2. 如果成员接受保释,则 br.accepted 设置为 true。 m.bail 设置为 n,m 在 n.associates 中

【问题讨论】:

  • 你能帮我解释一下这部分吗? class_name:您的协会中的“成员”
  • 您能否也发布成员表?在给定的上下文中,成员属于保释金似乎很奇怪。可能还想将 foreign_key: "candidate_id" 添加到 BailRequest 上的所属项
  • Kick Buttowski 工程师mnky:我添加了一些解释和代码。
  • engineersmnky 看来我不需要 Member.bail 的 foreign_key,因为它本身就是 associates 的 foreign_key,它不希望密钥像另一个表或这里那样在“其他地方”在同一个表中,但在另一列中。我的结论是 BailRequest.candidate 也不需要 foreign_key 属性,因为它本身包含引用并且看起来不像“其他地方”。实际测试过,但没有变化
  • @randmin,我刚刚创建了一个简单的 Rails 应用程序,只有这 2 个模型和 2 个迁移和 sqlite 数据库,当我创建 BailRequest 时它工作得很好,你的应用程序上还有其他东西我们没有看到,这种关系正常工作,您认为可能相关的任何额外代码?

标签: ruby-on-rails associations customcolumn


【解决方案1】:

在迁移文件中,我改变了

t.references :candidate, index: {:unique=>true}

t.integer :candidate_id, index: {:unique=>true}, foreign_key: true

并重新运行迁移。它现在正在 Rails 控制台上运行。感谢 arieljuod 的努力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2017-03-15
    • 2011-09-07
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多