【发布时间】: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