如果记录与Array中的任何ID具有相同的id,请选择记录

时间:2016-05-24 14:17:20

标签: ruby-on-rails postgresql activerecord has-many

我无法找到正确的语法和运算符来检查记录是否与存储在数组中的任何ID具有相同的ID。是否有has any?函数或类似函数?

@problem = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)

@pretreatments =  Treatment.joins(:remedies_treatment).where(:remedies_treatment_remedy_id == @problem)

我已将代码更新为:

 ids = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)

 @pretreatments = Treatment.joins(:remedies_treatments).where(remedies_treatments: { remedy_id: @problem })

但是我现在得到的错误是:

     SELECT "treatments".* FROM "treatments" INNER JOIN "remedies_treatments" ON "remedies_treatments"."treatment_id" = "treatments"."id" WHERE "remedies_treatment"."remedy_id" IS NULL
Completed 500 Internal Server Error in 157ms (ActiveRecord: 17.0ms)

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "remedies_treatment"
LINE 1: ...atments"."treatment_id" = "treatments"."id" WHERE "remedies_...
                                                             ^
: SELECT "treatments".* FROM "treatments" INNER JOIN "remedies_treatments" ON "remedies_treatments"."treatment_id" = "treatments"."id" WHERE "remedies_treatment"."remedy_id" IS NULL):
  app/controllers/treatments_controller.rb:116:in `index'



ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "remedies_treatment"
LINE 1: ...atments"."treatment_id" = "treatments"."id" WHERE "remedies_...
                                                             ^
: SELECT "treatments".* FROM "treatments" INNER JOIN "remedies_treatments" ON "remedies_treatments"."treatment_id" = "treatments"."id" WHERE "remedies_treatment"."remedy_id" IS NULL
        from C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/activerecord-4.2.5/lib/active_record/connection_adapters/postgresql_adapter.rb:592:in `async_exec'

2 个答案:

答案 0 :(得分:0)

使用ActiveRecord,您可以搜索数据库中的匹配记录:

@problem = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)
@pretreatments =  Treatment.joins(:remedies_treatment).where(:remedies_treatment_remedy_id: @problem)

这使用Hash子句的where语法,指定您要检索remedies_treatment_remedy_id包含@problem中任何值的任何记录。

答案 1 :(得分:0)

由于您希望匹配ID,因此请获取列表,并在下一个查询中使用它:

ids = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)

Treatment.joins(:remedies_treatments).where(remedies_treatments: { remedy_id: ids })

注意:您应该在Treatment中拥有以下关系:

class Treatment
   has_many :remedies_treatments
end