我有一个包含 3 个模型的应用程序:租户、部门、标准。
# app/models/department.rb
class Department < ActiveRecord::Base
attr_accessible :name, :abbr
has_many :renter_departments
has_many :renters, :through => :renter_departments
end
和
# app/models/criterium.rb
class Criterium < ActiveRecord::Base
attr_accessible :name
has_many :renter_criteria
has_many :renters, :through => :renter_criteria
end
我正在尝试在 Renter 模型中创建两个范围,让我可以按部门和标准找到租户。
这是我的代码:
# app/models/renter.rb
class Renter < ActiveRecord::Base
# Relationships
has_many :renter_departments
has_many :renter_criteria
has_many :departments, :through => :renter_departments
has_many :criteria, :through => :renter_criteria
# Scopes
scope :from_department, lambda { |abbr| joins(:departments).where("abbr = ?", abbr) }
scope :has_criterium, lambda { |criterium| joins(:criteria).where("name = ?", criterium) }
end
使用
Renter.from_department("SCS")
或者
Renter.has_criterium("Economic considerations")
自行工作。但是,当我尝试将它们链接起来时,
Renter.from_department("SCS").has_criterium("Economic considerations")
我收到一条错误消息:
Renter Load (0.3ms) SELECT "renters".* FROM "renters" INNER JOIN "renter_departments" ON "renter_departments"."renter_id" = "renters"."id" INNER JOIN "departments" ON "departments"."id" = "renter_departments"."department_id" INNER JOIN "renter_criteria" ON "renter_criteria"."renter_id" = "renters"."id" INNER JOIN "criteria" ON "criteria"."id" = "renter_criteria"."criterium_id" WHERE (abbr = 'SCS') AND (name = 'Economic considerations')
SQLite3::SQLException: ambiguous column name: name: SELECT "renters".* FROM "renters" INNER JOIN "renter_departments" ON "renter_departments"."renter_id" = "renters"."id" INNER JOIN "departments" ON "departments"."id" = "renter_departments"."department_id" INNER JOIN "renter_criteria" ON "renter_criteria"."renter_id" = "renters"."id" INNER JOIN "criteria" ON "criteria"."id" = "renter_criteria"."criterium_id" WHERE (abbr = 'SCS') AND (name = 'Economic considerations')
ActiveRecord::StatementInvalid: SQLite3::SQLException: ambiguous column name: name: SELECT "renters".* FROM "renters" INNER JOIN "renter_departments" ON "renter_departments"."renter_id" = "renters"."id" INNER JOIN "departments" ON "departments"."id" = "renter_departments"."department_id" INNER JOIN "renter_criteria" ON "renter_criteria"."renter_id" = "renters"."id" INNER JOIN "criteria" ON "criteria"."id" = "renter_criteria"."criterium_id" WHERE (abbr = 'SCS') AND (name = 'Economic considerations')
此外,
>> Renter.from_department("SCS").class
=> ActiveRecord::Relation
>> Renter.has_criterium("Economic considerations").class
=> ActiveRecord::Relation
关于我做错了什么的任何想法?