我在rails 4<
中转换rails 2 scope语法时遇到问题
类地区<的ActiveRecord :: Base的
has_many:位置
结束
类位置<的ActiveRecord :: Base的
belongs_to:region
范围:允许,lambda {| p_id |
{:joins => “在pl.location_id = locations.id上左加入person_locations pl”,
:conditions => [“pl.person_id =?AND pl.active ='是'”,p_id]}
} 的
#where pl = person_location
端
类PersonLocation<的ActiveRecord :: Base的
belongs_to:location
端
类LocationsController< ApplicationController的
def指数
@locations = @ region.locations.permitted(current_person.id).active.all(:order =>“name”)
respond_to do | format |
format.html #index.html.erb
结束
结束
端
答案 0 :(得分:1)
也许
scope :permitted, ->(p_id) { joins("left join person_locations pl on pl.location_id = locations.id").where("pl.person_id = ? AND pl.active = 'Yes'", p_id) }
答案 1 :(得分:1)
我会写:
scope :permitted, lambda { |id|
joins('left join person_locations pl on pl.location_id = locations.id').
where(pl: { person_id: id, active: 'Yes' })
}
或者,如果可以将person_locations
的关联添加到Location
模型中:
has_many :person_locations
scope :permitted, lambda { |id|
joins(:person_locations).where(person_locations: { person_id: id, active: 'Yes' })
}