Selecting all Records if Record has any of the ID's from Array

帅比萌擦擦* 提交于 2019-12-02 16:59:00

问题


Good Morning Overflow.

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

Here is my Treatments controller.

@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])

This is error from the console

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

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?

The Treatment model.

class Treatment < ActiveRecord::Base

  has_and_belongs_to_many :remedy

end

The Remedy Model.

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


回答1:


Selecting record by ids array is done with a query:

Record.where(id: 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)


来源:https://stackoverflow.com/questions/37408697/selecting-all-records-if-record-has-any-of-the-ids-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!