2011-06-11 40 views
1

爲了在用戶的「顯示」頁面上顯示這些記錄,我很難拔出一組與用戶自相關的記錄。在控制器計數關係中尋找自我參照

這裏的想法:

用戶(current_user)速率之外的兩個用戶(user_auser_b)之間的兼容性。他們可以對兼容性進行正面評價或負面評價:評價兩個「兼容」用戶在user_a和user_b之間創建一個positive_connection,並將它們評爲「不兼容」會創建一個negative_connection。所以有positive_connection,negative_connection和user的模型。

現在我需要顯示只有那些用戶overall_positively_connected_to(@user)(即其中positive_connections_to(@user).count > negative_connections_to(@user).count)

這是我必須的,但我不能得到任何進一步的:

用戶模式:

def overall_positive_connected_to(user) 
     positive_connections_to(user).count > negative_connections_to(user).count 
    end 


    def positive_connections_to(user) 
     positive_connections.where("user_b_id = ?", user) 
    end  

    def negative_connections_to(user) 
     negative_connections.where("user_b_id = ?", user) 
    end 

控制器

@user.user_bs.each do |user_b| 
    if user_b.overall_pos_connected_to(@user) 
    @compatibles = user_b 
    end 
end 

代碼中,我控制器顯然是錯誤的,但我應該怎麼做呢?我對rails(和sql)完全陌生,所以可能做了一些天真的事情。

任何幫助將是偉大的。

回答

1

我也是說得你有3種型號

  • 用戶(ID,姓名)
  • PositiveConnection(user_a_id,user_b_id)
  • NegativeConnection(user_a_id,user_b_id)

或者類似的東西。

我覺得你只是想2款 爲方便起見,我要重命名的關係作爲 「FROM_USER」 和 「to_user」

  • 用戶(ID,姓名)
  • 連接(價值:整數,from_user_id,to_user_id)

其中值爲-1的負數爲 ,+1爲正值。

現在我們可以做這樣的事情 (注:你需要理清確切的語法,如:foreign_key和:源,和東西)

class User 

    has_many :connections, :foreign_key => "from_user_id" 
    has_many :connected_users, :through => :connections, :source => :to_user 

    def positive_connections 
    connections.where(:value => 1) 
    end 

    def negative_connections 
    ... 
    end 

end 

但是,我們現在也有一個框架創建一個複雜的SQL查詢 (同樣你需要填寫空格...但類似)

class User 

    def positive_connected_users 
    connected_users.joins(:connections).group("from_user_id").having("SUM(connections.value) > 0") 
    end 

end 

這倒不去上班 但對於一個真正的解決方案

(它可能會更好想到在純SQL術語)

種僞代碼
+0

感謝馬修 - 那正是我一直在尋找的。事實上,我發現最終更簡單地完全改變我的模型,以便用戶首先建立兩個其他用戶之間的連接,然後對該連接進行投票。不像您的解決方案那麼優雅,但它適用於我的目的。 – jonic 2011-06-14 09:05:51

+0

是的,我應該建議你打出一個單獨的模型來兌現這些數字。否則,任何大型數據集都會變慢。你也可以考慮Mongo,因爲它可以很容易地做到這一點。請查看https://github.com/vinova/voteable_mongo,因爲您可以對此使用類似的想法 – 2011-06-15 06:44:27