开发者

Rails / Ruby: Getting a subset of objects after a .find query

@video = Video.find(params[:id])

Video has a parameter called description. I would like to get a subset of @video where :description is empty. I'm sure there's an inline .each type statement that would do开发者_StackOverflow中文版 it but have no idea how.

Thanks


For starters, in your example code you're only retrieving one record. To retrieve all records, you'd have to call:

@videos = Video.all

To get a subset, it depends how you want to do it. You can either do it when you're querying the database:

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

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

Or, you could partition your @videos array using a Ruby method:

# 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 is a method in Enumerable which iterates through an array and returns the elements where the block argument evaluates to True:

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


Do you mean something like:

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

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


Try

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

That should pull all the videos with null or empty description. Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜