Rails 连接查询

问题描述

我对 Rails 还很陌生,老实说,即使经过多次研究,我仍然在为查询而苦苦挣扎。 这是我的简单架构:

enter image description here

所以基本上,一个问题有很多选项,一个选项属于一个问题并且有很多答案,一个答案属于一个选项并且有很多用户。

我认为没有必要发布模型代码,因为它就像我上面提到的一样。

我想要做的是给出一个问题选项,看看特定用户是否已经检查过它(如果有与给定 id_option、user_id 和 user_type 匹配的行,请查看答案表)。所以在我的 haml 循环中,当显示不同的问题选项时,我正在调用我的 question_option 模型的方法,就像这样:

- question.question_option.all.each do |option|
    #{option.title}
    .check
        - if option.selected_by(current_actor)
            = check_box_tag(option.id,"checked",true,class: 'styled-checkbox')
        - else
            = check_box_tag(option.id,false,class: 'styled-checkbox')

和调用的方法:

def selected_by(answerer)
  answer_match =    
    ::Vacancies::QuestionOption
      .joins(:answers)
      .where(answerer_id: answerer.id,answerer_type:answerer.type )
  response = answer_match.find(self.id)
  return response
end

此方法位于我的 QuestionOption 模型中,不会导致任何错误,但它永远无法工作。 你能帮我转换这个查询以使其与 ActiveRecord 一起使用吗?谢谢

解决方法

试试下面的代码。它检查用户在问题的参数中传递的任何答案。我想这也是你打算做的-

def selected_by(answerer)
  answers =    
    Answer.where(answerer_id: answerer.id,answerer_type:answerer.type,id_option: self.id)

  answers.exists?
end

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...