首页 文章

将导轨范围导轨2.2升级到导轨4.2 [关闭]

提问于
浏览
-2

我在rails 4 <转换rails 2 scope语法时遇到了问题

class Region <ActiveRecord :: Base
has_many:位置
结束

class Location <ActiveRecord :: Base
belongs_to:region scope :permitted, lambda {|p_id| {:joins => "left join person_locations pl on pl.location_id = locations.id", :conditions => ["pl.person_id = ? AND pl.active = 'Yes'", p_id]} }
#where pl = person_location
结束

class PersonLocation <ActiveRecord :: Base
belongs_to:location
结束

class LocationsController <ApplicationController
def index @locations = @region.locations.permitted(current_person.id).active.all(:order => "name")
respond_to do | format |
format.html #index.html.erb
结束
结束
结束

  • List item

2 回答

  • 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' })
    }
    
  • 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) }
    

相关问题