简体   繁体   中英

Rails 5 query for a condition in a third table using joins?

this are my models - first:

 class Negocio < ApplicationRecord
  has_many :cuenta_clientes
end

second

class CuentaCliente < ApplicationRecord
  belongs_to :negocio
  has_many :pago_clientes
 end

and third:

class PagoCliente < ApplicationRecord
  belongs_to :cuenta_cliente
end

I want to select all the PagoCliente that a Negocio has. But there is no references between Negocio and PagoCliente (and i cannot modify tables and relations) so this is my attempt:

 pagos = PagoCliente.joins(cuenta_cliente: :negocio).where(negocio: {id: params[:negocio_id}])

but this is my error output:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "negocio"
LINE 1: ...cios"."id" = "cuenta_clientes"."negocio_id" WHERE "negocio"....

so, Which is the correct syntax for this query? thanks. I'm using Postgres...

if you are getting params[:negocio_id] you can do this way

1-

cuenta_cliente_ids= Negocio.find(params[:negocio_id]).cuenta_clientes.pluck(:id)

2-

pago_clientes = PagoCliente.where("cuenta_cliente_id IN (?)", cuenta_cliente_ids)

however with your query i think there is typo here i modify it

 pagos = PagoCliente.joins(cuenta_cliente: :negocio).where(negocios: {id: params[:negocio_id]})

ps correct me if i'm wrong

该表是复数的,请尝试:

pagos = PagoCliente.joins(cuenta_cliente: :negocio).where(negocios: {id: params[:negocio_id}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM