0
我有一個應用程序有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
我試圖使承租人模式,將讓我按部門和繞圈找租房兩個作用域。
這裏是我的代碼:
# 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
什麼我做錯了任何想法?
更改'範圍:has_criterium,拉姆達{|繞圈|將(:criteria).where(「name =?」,Criterium)}加到'scope:has_criterium,lambda {| criterium | join(:criteria).where(「criteria.name =?」,Criterium)}'並且解決它。謝謝! – Vidur