2011-04-20 31 views
2

影片表下一個對象的問題

id 
title 
votes_count 

視頻控制器

def show 
@video = Video.find(params[:id]) 
@next_video = Video.order("votes_count DESC").where("votes_count < ?", @video.votes_count).first 
@previous_video = Video.order("votes_count ASC").where("votes_count > ?", @video.votes_count).first 
end 

的問題是,有一些具有相同votes_count數量的視頻。當我將votes_count <更改爲votes_count < =它開始在2個視頻之間循環。有任何想法嗎?謝謝。

+0

但你想如何工作? – fl00r 2011-04-20 18:43:40

回答

3

解決這個問題的主要關鍵是,你需要明確包括一個輔助排序字段,這將給你的決心,以解決行相同的問題votes_count。您還需要將>=分成兩個單獨的子句,因爲您只希望在主要爲=時評估輔助字段。

現在,對於加分,我也要去重構你的代碼爲你的模型方法,讓你的控制器將成爲只是......

def show 
    @video = Video.find params[:id] 
end 

而且你的模型變得...

def next 
    self.class. 
    order("votes_count, id"). 
    where("votes_count > :votes_count OR (votes_count = :votes_count AND id > :id)", attributes.symbolize_keys).first 
end 

def previous 
    self.class. 
    order("votes_count DESC, id DESC"). 
    where("votes_count < :votes_count OR (votes_count = :votes_count AND id < :id)", attributes.symbolize_keys).first 
end 

現在在你看來,你可以直接參考@video.next@video.previous

+0

非常感謝。你救了我的一天! – rails101 2011-04-20 20:27:36

0

讓我們增加一些新的東西進入你的Video型號:

class Video < ActiveRecord::Base 
    def next(column = 'votes_count', order = 'DESC') 
    pos = self.position(column, order) 
    on_position(pos - 1, column, order) if pos > 0 
    end 

    def previous(column = 'votes_count', order = 'DESC') 
    pos = self.position(column, order) 
    on_position(pos + 1, column, order) 
    end 

    private 

    def position(column, order) 
    order_by = "#{column} #{order}" 
    arrow = order.capitalize == "ASC" ? "<=" : "=>" 
    Video.where("#{column} #{arrow} (?)", self.send(column)).order(order_by).count 
    end 

    def on_position(pos, column, order) 
    order_by = "#{column} #{order}" 
    arrow = order.capitalize == "ASC" ? "<=" : "=>" 
    Video.order(order_by).offset(pos).first 
    end 

end 

而且你的控制器

def show 
    @video = Video.find(params[:id]) 
    @next_video = @video.next 
    @previous_video = @video.previous 
end 

注意,我沒有測試過它,所以它可能是馬車。所有錯誤放在評論:)

+0

當有3個視頻具有相同的votes_count時,它開始在這些視頻之間循環。下一個視頻總是與視頻相同vote_count – rails101 2011-04-20 19:07:26

+0

瞭解:)我會認爲 – fl00r 2011-04-20 19:13:02

+0

謝謝。我現在正在嘗試。 – rails101 2011-04-20 19:30:25

0

你需要阻止它返回相同的視頻

@next_video = Video.order("votes_count DESC").where("votes_count < ? AND id !=", @video.votes_count, @video.id).first 

您應該還可能添加一個二級排序(可能通過id或created_at),以便在票數相等時順序一致。