三种模式的教授,专业知识和专业知识教授(联接表)。我想使用has_many activerecord结构,但是当我调用 Expertise.professors.all 时,出现错误
* NoMethodError(类别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
有什么想法我错过了吗?
答案 0 :(得分:1)
您无法致电Expertise.professors
。您首先需要加载
expertise = Expertise.first
然后您可以得到所有教授
expertise.professiors.all
以同样的方式,您可以获得特定教授的所有专业知识。