2013-05-13 76 views
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)}"} 

個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
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) 
} 
+0

'嘗試沒有更新一block' – Bruno 2013-05-13 14:13:12

+0

創建進程內對象 - 對不起爲 – PinnyM 2013-05-13 14:30:15

+0

我再爛,用'reverse' - 不是'desc'。更新。 – PinnyM 2013-05-13 17:13:25

相關問題