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

vehicle/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
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 に答える