2012-02-25 49 views
0

我是新來的回報率並沒有在10年左右做過任何Web編程用戶回答,所以請善待......數據庫查詢發現項目沒有以前

我有兩個表,問題和響應。答案屬於問題和問題 - 有很多答案。我試圖做一個查詢,將查找一個隨機問題的「開放」是真實的,其回答不包括任何具有特定ID的用戶。這是哪裏的東西站在現在:

offset = rand(Question.joins(:responses).where('responses.user_id <> ? and open = ?',  current_user.id, "true").count) 
@question = Question.joins(:responses).where('responses.user_id <> ? and open = "true"', current_user.id, "true").at(offset) 

有一個在我的數據庫,其地位是開放的,尚未使用ID = 1的用戶回答的問題,但這些查詢返回什麼。在此先感謝您的幫助!

回答

0

我沒有類似你這樣的模式,所以這是一種在黑暗中拍攝的,buuut ...

你不想字符串「true」傳遞到您的查詢,因爲open不會等於字符串「true」。它是一個布爾值,而不是一個字符串。想必。

因此,嘗試這樣的事情,而不是:

offset = rand(Question.joins(:responses).where('responses.user_id <> ? and open = ?',  current_user.id, true).count) 
@question = Question.joins(:responses).where('responses.user_id <> ? and open = ?', current_user.id, true).at(offset) 

沒有承諾,但它是一個開始。

我其實想到了一個更簡單的方法來完成這一點,而不是使用兩個單獨的查詢!

試試這個:

Question.joins(:responses).where('responses.user_id <> ? and open = ?', current_user.id, true).order('RAND()').first 

這不會等東西的SQLite沒有一個RAND()運營工作,但除此之外,它會給你滿足的標準,剩下的一個隨機記錄。

+0

我同意這可能是問題所在。我有一種感覺,軌道活動記錄處理它,但我會檢查。我還會直接看到數據庫中有什麼價值,例如mysql提示符或pgadmin 3數據瀏覽器等。如果它只有一個「1」,那麼嘗試('open = 1') – 2012-02-25 03:54:44

1

打破它,並檢查配件:

What does rand(Question) return ? 
What does rand(Question.joins(:responses) return ? 
What does Question.joins(:responses).where(...) return ? 
What does Question.where 'responses.user_id <> ? and open = true', current_user.id) return 

在軌控制檯執行此操作。如果current_user不可用,請找到您想要的用戶,並將current_user設置爲等於id或僅使用一個id號碼,例如, '23'

0
Question.joins(:responses).where('user_id <> ? and open = ?', current_user, true).order('RANDOM()').first