ActiveRecord无法识别belongs_to关联

问题描述 投票:0回答:1

我有老师和学生模特,学生belongs_to :teacher, optional: true和老师has_many :students

在rails控制台中,当我尝试Teacher.find(11).students时,它会返回第11位老师的学生(如预期的那样)

但是,当我尝试Student.find(3).teachers时,它会返回一个错误:NoMethodError (undefined method 'teachers' for #<Student..>)

注意:第11名教师和第3名学生存在,并在相关表格中有记录

ruby-on-rails ruby-on-rails-5
1个回答
1
投票

学生belongs_to :teacher,所以它应该是

Student.find(3).teacher

注意teacher的单数形式

© www.soinside.com 2019 - 2024. All rights reserved.