has_many中的未知列错误通过升级到Rails 5后的关联

时间:2019-05-17 12:47:08

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

我最近将一个应用程序从Rails 4升级到了Rails5。我已经开始收到一个以前起作用的关联上的Unknown Column错误。

我有3个这样的课程:

class User < ActiveRecord::Base
  has_many :department_users
  has_many :departments through: :department_users
  has_many :writable_staffs,  -> {where('department_users.write = 1').uniq}, through: :departments, source: :staffs
end
class Department < ActiveRecord::Base
  has_many :department_users
  has_many :users, through: :department_users
end
class Department < ActiveRecord::Base
  has_many :department_users
  has_many :users, through: :department_users
end
class DepartmentUse < ActiveRecord::Base
  belongs_to :user
  belongs_to :department
end

在department_users表中,有一个布尔列“写”。

如果我运行User.first.writable_staffs,则会收到以下错误:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'department_users.write' in 'where clause': SELECT `staffs`.* FROM `staffs` WHERE (department_users.write = 1)

我可以通过将user.rb中的writable_staffs关联替换为

来进行修复
  has_many :writable_departments, -> {where('department_users.write = 1')}, through: :department_users, source: :departments
  has_many :writable_staffs, through: :writable_departments, source: :staffs

哪个很好,但是我不明白为什么先前的代码停止工作?有人可以照亮它吗?

1 个答案:

答案 0 :(得分:0)

似乎问题出在使用被轨5折旧的“ uniq”。在将其替换为unique之后,原始代码仍像以前一样运行。