2012-08-04 438 views
2

因此,我有這個「高級」查詢(沒有太多,真的),我想將它翻譯成Ruby Active Record的語法。將一些SQL查詢轉換爲活動記錄

SELECT microposts.* 
FROM microposts 
WHERE user_id IN 
     (SELECT r.followed_id as uid 
     FROM relationships r 
     WHERE follower_id = 1 
     UNION 
     SELECT u.id as uid 
     FROM users as u 
     WHERE id = 1 
    ) 
ORDER BY microposts.created_at DESC 

當時的想法是檢索所有微柱爲用戶1和用戶1,隨後在遞減順序創建用戶,但我真的不知道如何翻譯這個容易使用Active Record的語法。

有沒有想法?

PS:由於要求在這裏是一些軌道方面:

我有3種型號:MicropostsUsersRelationships

  • 關係是一個處理所有用戶關係(follower/follow stuff)的連接表。
  • 用戶通過關係有很多follow_users/followers。
  • 用戶有很多microhoops,microhoops有一個用戶。

謝謝。

+0

感謝您的可讀性修復,ypercube :) – 2012-08-05 00:14:50

回答

1

你的查詢是非常具體的,因此你最好的選擇是使用SQL編寫它的很大一部分,或者嘗試像squeel這樣的gem,它可以幫助從ActiveRecord生成非常定製的SQL。

不過,這應該做的工作,沒有額外的寶石:

user_id = ... #Get the user_id you want to test 
Micropost.where("user_id IN 
    (SELECT r.followed_id as uid 
    FROM relationships r 
    WHERE follower_id = ?) 
    OR user_id = ? 
    ", user_id, user_id).order("created_at desc") 
1

關於Ruby但SQL不知道可以簡化爲:

SELECT microposts.* 
FROM microposts 
WHERE user_id IN 
     (SELECT r.followed_id as uid 
     FROM relationships r 
     WHERE follower_id = 1 
    ) 
    OR user_id = 1 
ORDER BY microposts.created_at DESC 
1

我的回答將承擔(因爲你在您的原始SQL查詢之外沒有提供ruby/rails-context)您有User模型,Micropost模型通過關係:microposts,以及Relationship模型通過關係:followingUser有許多相關的MicropostRelationship實例。你可以做

u = User.find(1) 
user.microposts + user.following.microposts 

,或者你可以內Micropost

def self.own_and_following(user) 
    user.microposts + user.following.microposts  
end 

移動到這一點的方法和調用Micropost.own_and_following(User.find(1))

這可能不是您要查找的內容,但鑑於您在Rails應用程序中提到的上述可能關係,聽起來像是類似於此的應該起作用。

+0

哦,對不起,我完全忘了指定我的模型和關聯。但你是對的,我會糾正它。 – 2012-08-05 00:12:12

+0

但這不是我正在尋找的,因爲這會給我用戶的微博,然後按順序跟隨用戶微博。我需要所有用戶和用戶的關注用戶microposts按日期分配。在某種程度上,拉嘰嘰喳喳,臉譜等。 – 2012-08-05 00:14:10

+0

AREL是否將'+ +'轉換爲UNION? – 2012-08-06 15:10:52

0

我只得到使用,其中,看起來很像的find_by_sql給我做,我不知道哪一個會更好:

Micropost.order('created_at DESC'). 
where('user_id in (select r.followed_id as uid from relationships as r where follower_id = ?) or user_id = ?', user.id, user.id) 

不知道有多好,這是,但它似乎工作。