2017-09-01 54 views
1

在我的聊天應用程序中,我想計算學生模型的回覆率。如何搜索字符串屬性中的標識(SQL)

我使用slug屬性跟蹤所有對話。這是一個這樣的字符串:270-77,這意味着這是學生270和招聘人員77之間的對話。

現在我想檢查一個學生有多少個對話。這裏是我的代碼:

def calculate_number_of_conversations(@student) 
    @conversations = Conversation.where("slug LIKE ?", "%#{params[@student]}") 
end 

重要的是,它應該在字符串的第一部分只搜索,因爲slug的第一個數字始終是一個學生的ID。

def calculate_number_of_conversations(@student) 
    @conversations = Conversation.where("slug LIKE ?", "%#{params[@student]}-") 
end 
+2

您在使用MySQL或PostgreSQL? – jarlh

+1

對於學生LIKE應該是'LIKE%270-%'對於招聘者LIKE應該是'LIKE%-77%'這應該在MySQL和PostgreSQL中工作 –

+0

Postgresql @jarlh。謝謝你們,會測試它! – crievino

回答

3

我不知道什麼是@student:到WHERE LIKE子句 -

+0

謝謝!我會看一看。該查詢爲我提供了包含student_id的所有對話。因此,如果我使用student_id「9」進行搜索,我會從ID爲9,99,297等的學生那裏獲得交談。我如何搜索特定號碼? – crievino

1

您可以添加 ''。我會寫我的例子,好像它是一個記錄。

你可以使用-,以確保它看起來只有學生:

@conversations = Conversation.where('slug LIKE ?', "#{@student.id}-%") 

但我認爲這是最好有明確的關係:

class Conversation < ApplicationRecord 
    belongs_to :student 
    belongs_to :recruiter 
end 

@conversations = @student.conversations 
+0

例如,當我嘗試搜索student_id 9時,它會以「9」的形式給我提供與student_ids的所有對話。所以也是297,99,91等。我應該如何只針對特定的字符串? – crievino