问题
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