【问题标题】:Upgrading rails scope rails 2.2 to rails 4.2 [closed]将 rails 范围 rails 2.2 升级到 rails 4.2 [关闭]
【发布时间】:2015-12-03 14:28:59
【问题描述】:

我在转换 rails 4 中的 rails 2 范围语法时遇到问题


类区域    has_many :locations
结束

类位置   belongs_to :region
  范围:允许,lambda {|p_id| {:joins => "在 pl.location_id = locations.id 上左加入 person_locations pl", :conditions => ["pl.person_id = ? AND pl.active = 'Yes'", p_id]} }

  #where pl = person_location
结束


类 PersonLocation    归属地:位置
结束


类 LocationsController    定义索引
     @locations = @region.locations.permitted(current_person.id).active.all(:order => "name")

      respond_to do |format|
        format.html # index.html.erb
       结束
    结束
结束

  • 列表项

【问题讨论】:

  • 你从来没有提到问题是什么。请提供更多细节。

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


【解决方案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) } 

?

【讨论】:

    【解决方案2】:

    我会写:

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

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2015-03-14
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多