问题
I am having trouble finding the right syntax and operator to check if a record has the same ID of any of the ID's stored in an Array. Is there a has any?
function or similar?
@problem = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)
@pretreatments = Treatment.joins(:remedies_treatment).where(:remedies_treatment_remedy_id == @problem)
I have updated the code to:
ids = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)
@pretreatments = Treatment.joins(:remedies_treatments).where(remedies_treatments: { remedy_id: @problem })
However the error I am getting now is:
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'
回答1:
Since you wish to match ids, so get the list, and use it in next query:
ids = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)
Treatment.joins(:remedies_treatments).where(remedies_treatments: { remedy_id: ids })
NOTE: You should have the following relation in Treatment
:
class Treatment
has_many :remedies_treatments
end
回答2:
Using ActiveRecord, you can search for matching records from the database:
@problem = Remedy.where(["LOWER(\"remedyName\") LIKE?", "%#{params[:searchremedy]}%".downcase]).pluck(:id)
@pretreatments = Treatment.joins(:remedies_treatment).where(:remedies_treatment_remedy_id: @problem)
This uses the Hash
syntax for the where
clause, by specifying that you want to retrieve any records where remedies_treatment_remedy_id
includes any value in @problem
.
来源:https://stackoverflow.com/questions/37416290/select-record-if-the-records-has-same-id-as-any-of-the-ids-in-the-array