0
@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 it but have no idea how.

Thanks

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Do you mean something like:

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

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

Comments

0

Try

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.