【问题标题】:Why is my Rails activerecord many-to-many through relationship not working为什么我的 Rails activerecord 多对多通过关系不起作用
【发布时间】:2019-12-19 08:50:04
【问题描述】:

三个模型Professor、Expertise & ExpertisesProfessor(连接表)。我想使用 has_many activerecord 结构,但是当我调用 Expertise.professors.all 时出现错误

*NoMethodError(未定义方法 `professors' for Class:0x000000000a1ddda0)*

我希望能够调用 Expertise.professors 和 Professor.expertise ???

我很喜欢使用 HABTM 而不是“has_many through”,但对于我的项目,我更喜欢使用“has_many through”关系,所以请如果我能在可能的情况下获得这些解决方案。

**professor.rb**
class Professor < ApplicationRecord
  has_many :expertise_professors
  has_many :expertises, through: :expertise_professors
end

**expertise.rb**
class Expertise < ApplicationRecord
  has_many :expertise_professors
  has_many :professors, through: :expertise_professors
end

**expertises_professor.rb**
class ExpertisesProfessor < ApplicationRecord
  belongs_to :expertise
  belongs_to :professor
end

我的架构文件

# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 2019_12_18_191008) do

  create_table "expertises", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "expertises_professors", id: false, force: :cascade do |t|
    t.integer "expertise_id", null: false
    t.integer "professor_id", null: false
  end

  create_table "professors", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

有什么我错过的想法吗?

【问题讨论】:

  • @MarekLipka 我添加了我收到的错误的 rails 控制台的屏幕截图。我现在正在 Rails 控制台中测试我的关联
  • 似乎 1) 或者您忘记保存更改 2) 或者您需要在 Rails 控制台中执行 reload! 3) 或者您必须执行弹簧停止 4) 或者您必须检查原因还有Expertise::ExpertiseProfessors 而不仅仅是ExpertiseProfessors
  • 另外,如果expertities_professors 是一个只有外键的连接表,那么为什么要使用has_many through 并让Rails 堆栈初始化一个模型。应该是has_and_belongs_to_many。您的表和模型名称符合命名约定。
  • @SebastianPalma。感谢您的答复。建议 1 到 3 我检查并在处理过程中不是问题。建议 4 希望我能从社区那里获得解决方案的想法,因为我不太确定这是来自
  • @AlokSwain 。谢谢 。我正在尝试通过构建将其视为 has_many。我试图更新我的关联来实现这一点。关于我需要进行的可能导致问题的其他更改的任何建议,即命名约定?

标签: ruby-on-rails ruby ruby-on-rails-5


【解决方案1】:

您不能拨打Expertise.professors。您首先需要加载 Expertise 的单个记录或对象,例如

expertise = Expertise.first

然后你可以得到所有教授

expertise.professiors.all

同样的方式,您可以获得特定教授的所有专业知识。

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-21
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多