2011-06-07 76 views
0

我希望你们中的一些sql大师可以帮助我在rails中构建一个相对复杂的(对我来说)查询。我有两个相关的模型,一个Story模型和一个Post模型。帮助构建一个复杂的数据库查询在rails中

class Story < ActiveRecord::Base 

attr_accessible :title 

    belongs_to :user 
    has_many :posts, 
     :dependent => :nullify 


class Post < ActiveRecord::Base 

    attr_accessible :contents 

    belongs_to :story, :touch => true 
    belongs_to :user, :touch => true 

每个故事实例都充当多个帖子实例的包装。我希望能够在数据库中搜索具有在特定时间范围内创建的帖子的故事,并且如果有一个故事在给定时间范围内创建了帖子,则返回所有故事属性以及故事最近创建的帖子(也包括所有属性)在时间范围内创建。我可以获取故事属性和post_id,但我无法弄清楚如何获取其他帖子属性。

以下是我在Post.rb得:

scope :within_user_preferred_date_range, lambda { |user| 
    where("posts.created_at BETWEEN ? AND ?", 
     (Time.now.midnight - user.preferences[:start_story_date_offset_in_days].days), 
     (Time.now - user.preferences[:end_story_date_offset_in_days].days)) } 

    #################################### 

    def self.close_timely_posts(user) 
    Post.includes(:story).within_user_preferred_date_range(user).select("DISTINCT(story_id)") 
    end 

这会产生下面的SQL查询,显然这,不正是我需要的:

←[1m←[35mPost Load (0.0ms)←[0m SELECT DISTINCT(story_id) FROM `posts` WHERE 
(posts.created_at BETWEEN '2011-06-03 07:00:00' AND 
'2011-06-06 19:34:40') ORDER BY posts.created_at DESC 
    ←[1m←[36mStory Load (0.0ms)←[0m ←[1mSELECT `stories`.* FROM `stories` WHERE (`stories`.`id` IN (70,57,53,55,16,54,51,56,52,60,59,58))←[0m 

任何帮助你可以给与这个查询将不胜感激!

回答

0

尝试修改您的代码:

def self.close_timely_posts(user) 
    Post.includes(:story).within_user_preferred_date_range(user).select("DISTINCT(story_id), posts.*") 
    end 
+0

嗯。根据您的建议导致以下错误消息: ←[1m←[35m Post Load(0.0ms)←[0m SELECT DISTINCT(story_id),* FROM'posts' WHERE(posts.created_at BETWEEN'2011-06-04 07: 00:00'AND'2011-06-07 23:31:24')ORDER BY posts.created_at DESC Mysql2 ::错误:您的SQL语法错误;查看与您的MySQL服务器版本相对应的手册 正确的语法在'* FROM'posts'附近使用WHERE(posts.created_at BETWEEN'2011-06-04 07:00:00'AND'2011-0'at line 1:SELECT DISTINCT(story_id), * FROM'posts' WHERE(posts.created_at BETWEEN ... – 2011-06-07 23:34:47

+0

[整理出错信息] ...'2011-06-04 07:00:00'AND'2011-06- 07 23:31:24')ORDER BY posts.created_at DESC – 2011-06-07 23:35:20

+0

我已更正查询 - 尝试以此形式 – 2011-06-08 04:12:23