Tom
Tom

Reputation: 180

Ruby on Rails - Active Record Query - Return items that only have an image

I'm redeveloping a site that has an image slider on the home page that shows 5 of the latest news stories, however, I only want it to show the latest 5 stories that have at least one image in the images table.

So my question is, how to I modify the below to return five records with images:

@slider_stories = Story.published.all(:limit => 50, :include => [:images])

Upvotes: 3

Views: 327

Answers (1)

fl00r
fl00r

Reputation: 83680

Something like that

@slider_stories = Story.published.all(:limit => 50, :include => [:images], :conditions => "DISTINCT(stories.id), stories.*, images.*")

or

@slider_stories_ids = Image.all(:select => "DISTINCT(story_id)").map(&:story_id)
@slider_stories = Story.published.all(:limit => 50, :include => [:images], :conditions => {:id => @lider_stories_ids})

Upvotes: 1

Related Questions