2011-03-11 11 views

回答

4

對於初學者來說,在你的代碼示例你只檢索一個記錄。要檢索所有記錄,你不得不撥打:

@videos = Video.all 

爲了得到一個子集,這取決於你怎麼想這樣做。你可以做到這一點,當你查詢的數據庫:

# Rails 2 
@videos = Video.find(:all, :conditions => ['description = ? OR description IS NULL', '']) 

# Rails 3 
@videos = Video.where('description = ? OR description IS NULL', '') 

或者,你可以使用Ruby的方法劃分您的@videos陣列:

# Find all our videos 
@videos = Video.all 

# And then pick the ones where the description attribute is blank 
@videos_with_blank_description = @videos.select { |v| v.description.blank? } 

Array#select是一種方法,其中Enumerable迭代通過數組,並返回其中塊參數的計算結果爲True的元素:

http://www.ruby-doc.org/core/classes/Enumerable.html#M001488

1

你的意思是這樣的:

#Rails 2.3: 
Video.all(:conditions => {:description => nil}) 

#Rails 3: 
Video.where(:description => nil) 
0

試試

@videos = Video.all(:conditions => [ "description IS NULL OR description = ?", '' ]) 

這應該拉空或空描述的所有視頻。祝你好運!