賃借人、部門、基準の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
レンターモデルで2つのスコープを作成して、部門別および基準別に賃借人を検索できるようにしようとしています。
これが私が持っているコードです:
# 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
私が間違っていることについて何か考えはありますか?