1

如何根据以下内容显示上一个/下一个链接vehicle.vehicle_status

在我的节目视图中:

- if @vehicle.previous
  = link_to "< Previous", @vehicle.previous
- if @vehicle.next
  = link_to "Next >", @vehicle.next

在我的模型中:

def previous
  ?
end

def next
  ?
end

车辆/index.html.haml 视图:

- @vehicles.each do |vehicle|
  %tr
    %td.dashbox{:class => vehicle.vehicle_status, :style =>'width:18px;', :onclick=>"top.location=#{vehicle_url(vehicle)}"}

模型中的车辆状态:

def vehicle_status
  if self.maintenance_status=='c1' or self.fuel_efficiency_status=='c1' or self.system_status=='c1'
  'c1'
  elsif self.maintenance_status=='c2' or self.fuel_efficiency_status=='c2' or self.system_status=='c2'
  'c2'
  elsif self.maintenance_status=='c4' or self.fuel_efficiency_status=='c4' or self.system_status=='c4'
  'c4'
  else
  'c3'
  end
end
4

1 回答 1

1
scope :previous, lambda { |vehicle| 
  where("vehicles.vehicle_status < ?", vehicle.vehicle_status).
    order(:vehicle_status).reverse
}

scope :next, lambda { |vehicle|
  where("vehicles.vehicle_status > ?", vehicle.vehicle_status).
    order(:vehicle_status)
}

def previous
  @previous ||= Vehicle.previous(self).first
end

def next
  @next ||= Vehicle.next(self).first
end

鉴于这vehicle_status是一个计算而不是静态字段,并且排序中涉及其他因素,您可以将范围修改为如下所示(使用 CASE 字符串的辅助方法):

def self.vehicle_status_sql
  <<-SQL
    CASE 
      WHEN 'c1' IN (maintentance_status, fuel_efficiency_status, system_status) THEN 'c1'
      WHEN 'c2' IN (maintentance_status, fuel_efficiency_status, system_status) THEN 'c2'
      WHEN 'c4' IN (maintentance_status, fuel_efficiency_status, system_status) THEN 'c4'
      ELSE 'c3'
    END
  SQL
end

scope :previous, lambda { |vehicle| 
  where("#{vehicle_status_sql} < :status OR (#{vehicle_status_sql} = :status AND (vehicles.odometer < :odometer OR (vehicles.odometer = :odometer AND vehicles.id < :id)))", 
    status: vehicle.vehicle_status, odometer: vehicle.odometer, id: vehicle.id).
  order("#{vehicle_status_sql} DESC, vehicles.odometer DESC")
}

scope :next, lambda { |vehicle| 
  where("#{vehicle_status_sql} > :status OR ((#{vehicle_status_sql} = :status AND (vehicles.odometer > :odometer OR (vehicles.odometer = :odometer AND vehicles.id > :id)))",
    status: vehicle.vehicle_status, odometer: vehicle.odometer, id: vehicle.id).
  order("#{vehicle_status_sql}, vehicles.odometer)
}
于 2013-05-13T13:47:36.203 回答