上一个/下一个链接基于模型的功能

时间:2013-05-13 13:39:38

标签: ruby-on-rails

如何根据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

vehicles / index.html.haml查看:

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

模型中的vehicle_status:

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

1 个答案:

答案 0 :(得分: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)
}