我有3个模型的应用程序:Renters,Departments,Criteria。
# 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
关于我做错的任何想法?
答案 0 :(得分:2)
您加入的表格中有多个name
列。将WHERE
子句设为renters.name
或departments.name
或使用适当的name
列。
答案 1 :(得分:1)
您需要在范围中引用表名:
scope :from_department, lambda { |abbr| joins(:departments).where("departments.abbr = ?", abbr) }
scope :has_criterium, lambda { |criterium| joins(:criteria).where("criteria.name = ?", criterium) }