如何在字符串属性(SQL)中搜索ID



在我的聊天应用中,我想计算学生模型的响应率。

我使用slug属性跟踪所有对话。这是这样的字符串:270-77,这意味着这是Student 270和招聘人员77之间的对话。

现在,我想检查一个学生进行了多少对话。这是我的代码:

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

重要的是,它只能在字符串的第一部分中进行搜索,因为slug中的第一个数字始终是学生的ID。

我不确定@student是什么。我会写我的示例,就像是记录一样。

您可以使用-来确保它仅在寻找学生:

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

,但我认为最好有明确的关系:

class Conversation < ApplicationRecord
  belongs_to :student
  belongs_to :recruiter
end
@conversations = @student.conversations

您可以将' - '添加到Where Like子句:

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

最新更新