【问题标题】:JOIN cannot find the column on the corret table in scopesJOIN 在范围内的 corret 表上找不到列
【发布时间】:2013-03-06 21:36:00
【问题描述】:

我有一些这样的模型:

class Student < ActiveRecord::Base
  belongs_to :Teacher
  scope :rich_students, joins(:teachers).order('students.money DESC')
end

然后是班主任

class Teacher < ActiveRecord::Base
  has_many :students
  belongs_to :Organization
end

然后:

class Organization < ActiveRecord::Base
  has_many :teachers 
end

现在我写一个这样的查询:

Student.rich_students.joins(:teachers).where("teachers.organization_id = ?", params[:id]).limit(5)

但这不起作用。它给了我错误:

Association named 'teachers' was not found;

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.2 rails-activerecord


    【解决方案1】:

    连接应该是

    Student.rich_students.joins(:teacher)

    ?

    【讨论】:

    • 所以当我们在连接(Blah)中使用某些东西时,“blah”不应该是复数形式吗?对吗?
    • 这通常是正确的。您可以在 rails 控制台中使用它来获得正确的结果。
    【解决方案2】:

    我认为您的学生“belongs_to”声明中应该有错误

    class Student < ActiveRecord::Base
      belongs_to :teacher
      scope :rich_students, joins(:teachers).order('students.money DESC')
    end
    

    “:teacher”而不是“:Teacher”

    希望它可以成为问题的原因......

    干杯

    【讨论】:

      猜你喜欢
      • 2020-11-23
      • 2021-06-18
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多