将导轨范围导轨2.2升级到导轨4.2

时间:2015-12-03 14:28:59

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord

我在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     结束    
结束  

  • 列表项

2 个答案:

答案 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' })
}