2011-06-07 75 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