2011-02-06 20 views
0

我正在組合一個小遊戲,人們在投票中看到另外兩個人根據他們之前輸入的一些興趣進行了很好的匹配,並且無法讓代碼執行什麼操作我想要。我們對他們的「朋友」的一些數據,我想做到以下幾點:有些智慧的Rails迭代

  1. 選擇他們的「朋友」
  2. 一個找到匹配的那個朋友
  3. 的。如果我不能找到任何朋友的比賽,我以前投票,得到一個隨機比賽

我想步驟1和2有點隨機,所以他們沒有看到朋友每次。我現在正在記錄選票,所以我已經有了他們的選票清單。這是我迄今爲止所做的,但無法弄清楚如何將兩者結合在一起。

found_new_match = false 

#Try connected users first 
# connected_users = current_user.get_connected_users 
connected_users = [] 

unless connected_users.blank? 
    user = connected_users.shuffle.first 
    @match = user.matches.first 
end 

# Here i'd like to detect whether we got through all our connections' matches 
while found_new_match == false do 
    found_new_match = true if @match = current_user.get_random_new_match 
end 

回答

1

假設你的代碼(獲取連接的用戶)可以正常工作,你的問題是關於如何將這種邏輯坍塌成一行的所有支持邏輯,下面應該很好地工作:

@match = current_user.get_connected_users.shuffle.first.try(:matches).try(:first) || current_user.get_random_new_match 

如果將「用戶的第一次匹配」(user.matches.first)分解爲其自己的訪問方法,則可以跳過看起來很糟糕的.try(:matches).try(:first)。你可以另一個因素「第一隨機匹配」到一個方便的方法上User,使得代碼將進一步縮短到:

@match = current_user.get_random_connected_match || current_user.get_random_new_match 

假設「get_random_connected_match」確實讓連接的用戶,洗牌出局的行爲選項,並從中提取第一個匹配項。重複重構和惡作劇。

+0

謝謝!我之所以首先提出的原因是因爲我只是想要得到一個結果,但很可能第一個選項已經被投票了,所以我希望在下一個選項之後這樣做,米只是不知道如何遍歷這些選項。 – user577808 2011-02-06 15:19:08

0

我把你的意見,並與去:

@match = current_user.get_random_connected_match || current_user.get_random_new_match 

在我的方法,我有:

connected_users = self.get_connected_users.map(&:id) 
my_voted_matches = self.votes.map(&:matching_id) 

Matching.first(:conditions => ["id NOT IN (?) AND (user_id IN (?) OR matched_id IN (?))", my_voted_matches.join(","), connected_users.join(","), connected_users.join(",")], :order => "RAND()")