dimanche 6 décembre 2015

Ruby on Rails with sqlite, trying to query and return results from the last 7 days?

Noob here, I'm trying to query my SQLite database for entries that have been made in the last 7 days and then return them. This is the current attempt

user.rb

def featuredfeed
      @x = []
      @s = []

      Recipe.all.each do |y|
        @x << "SELECT id FROM recipes WHERE id = #{y.id} AND created_at > datetime('now','-7 days')"
      end

      Recipe.all.each do |d|
        @t = "SELECT id FROM recipes where id = #{d.id}"
        @x.each do |p|
          if @t = p
            @s << d
          end
        end

      end
      @s          
  end

This code returns each recipe 6(total number of objects in the DB) times regardless of how old it is.

@x should only be 3 id's

@x = [13,15,16]

if i run

SELECT id FROM recipes WHERE id = 13 AND created_at > datetime('now','-7 days')

1 Rows returned with id 13 is returned

but if look for an id that is more than 7 days old such as 12

SELECT id FROM recipes WHERE id = 12 AND created_at > datetime('now','-7 days')

0 Rows returned

I'm probably over complicating this but I've spent way too long on it at this point.

the return type has to be Recipe.

Aucun commentaire:

Enregistrer un commentaire