如果记录具有来自阵列的任何ID,则选择所有记录 [英] Selecting all Records if Record has any of the ID's from Array

查看:66
本文介绍了如果记录具有来自阵列的任何ID,则选择所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好溢出.

我在尝试选择所有ID都存储在名为 @problem 的数组中的所有治疗时遇到问题.

I'm having a problem trying to select all Treatments that have any of the ID's stored in an array called @problem.

这是我的治疗负责人.

@problem = Remedy.find_by_sql(["SELECT id FROM remedies WHERE LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase])

 query = "SELECT * FROM treatments INNER JOIN remedies_treatments on treatments.id = remedies_treatments.treatment_id WHERE remedies_treatments.treatment_id LIKE ?"
 @pretreatments = Treatment.find_by_sql([query, @problem])

这是来自控制台的错误

ActiveRecord::StatementInvalid (PG::SyntaxError: ERROR:  syntax error at or near ","
LINE 1: ...d WHERE remedies_treatments.treatment_id LIKE 233,234,224

'LIKE'运算符可能不是我要执行的操作所需要的-我尝试使用ANY运算符,但也无济于事.问题是否源于它是整数数组的事实?

The 'LIKE' operator is probably not what I need for what I'm looking to do - I tried using the ANY operator but to no avail either. Does the problem stem from the fact it is an array of integers?

治疗模式.

class Treatment < ActiveRecord::Base

  has_and_belongs_to_many :remedy

end

补救模式.

class Remedy < ActiveRecord::Base

  has_and_belongs_to_many :treatments, dependent: :destroy
end

有一个后续帖子,我的问题已得到解决

There is a follow up post where my issue was resolved here

推荐答案

通过ID数组选择记录是通过查询完成的:

Selecting record by ids array is done with a query:

Record.where(id: ids)

其中 ids 是ids数组.可以用另一个查询替换它.

where ids is ids array. It can be replaced with another query.

对于您的情况,按匹配名称选择补救措施如下:

For your case selecting remedies by match name will be as follows:

ids = Remedy.where("LOWER(remedyName) LIKE ?", name.downcase).pluck(:id)

这篇关于如果记录具有来自阵列的任何ID,则选择所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆