2016-03-11 2 views
2

В настоящее время имеющих запрос для фильтра с параметрами premium_amount_lower_range, premium_amount_upper_range, application_date_lower_range, application_date_upper_range, insurance_type_idСложные Postgres запрос в рельсах

@filtered_quotes = current_user.insurance_subscribers.includes(:insurance_types).includes(:insurance_subscribers_types, :insurance_subscribers_types_carriers). 
        premium_amount(params[:dashboard][:premium_amount_lower_range], params[:dashboard][:premium_amount_upper_range]). 
        duration(params[:dashboard][:application_date_lower_range], params[:dashboard][:application_date_upper_range]). 
        insurance_type(params[:dashboard][:insurance_type_id]) 

Но теперь нужно фильтровать по статусу также. Возникла проблема с этим. У меня есть столбец статуса в таблицах insurance_subscribers и insurance_subscribers_types_carriers, оба столбца перечислены.

Я пытался добавить, где положение как

@filtered_quotes = current_user.insurance_subscribers.includes(:insurance_types).includes(:insurance_subscribers_types, :insurance_subscribers_types_carriers). 
       where("insurance_subscribers_types_carriers.status = 1") 
#    ... 

Это дает мне ошибку PG::UndefinedTable: ERROR: missing FROM-clause entry for table "insurance_subscribers_types_carriers"

, но когда я пытаюсь сделать как

@filtered_quotes = current_user.insurance_subscribers.includes(:insurance_types).includes(:insurance_subscribers_types, :insurance_subscribers_types_carriers). 
      where(status: 1) 
#   .... 

Это поставит где пункт о insurance_subscribers ,

Попытка добавить простой раздел where WHERE insurance_subscribers_types_carriers.status = 1 в вышеуказанный запрос, но имеющий столько проблем с этим запросом.

Ассоциации

insurance_subscriber.rb

has_many :insurance_subscribers_types, dependent: :destroy 
has_many :insurance_types, through: :insurance_subscribers_types 
has_many :insurance_subscribers_types_carriers, through: :insurance_subscribers_types 

insurance_types.rb

has_many :insurance_subscribers, through: :insurance_subscribers_types 
has_many :insurance_subscribers_types 
has_many :insurance_subscribers_types_carriers 

insurance_subscriber_type.rb

belongs_to :insurance_subscriber 
belongs_to :insurance_type 
has_many :carriers, through: :insurance_subscribers_types_carriers 
has_many :insurance_subscribers_types_carriers, dependent: :destroy 

insurance_subscr ibers_types_carrier.rb

belongs_to :carrier 
belongs_to :insurance_subscribers_type 
+0

Какова связь между 'страховой _types'' insurance_subscribe rs' и 'insurance_subscribers_type_carriers'? Пожалуйста, добавьте все ассоциации – RSB

+0

Добавленные ассоциации – SpunkyLive

+0

Пробовали ли вы внешние внешние соединения вручную, а не включены? – Thorin

ответ

3

Если вы хотите добавить queries через связанные модели, сначала вам нужно присоединиться к ним. Поскольку у вас есть has_may :through ассоциации, вы можете сделать хотите вы хотите следующим образом:

InsuranceSubscriber.joins(insurance_subscriber_types: :insurance_subscribers_types_carriers) 
.includes(:insurance_types, :insurance_subscribers_types, :insurance_subscribers_types_carriers) 
.where("insurance_subscribers_types_carriers.status = ?", 1) 

Как вы видите, вы можете присоединиться и ссылаться на свои ассоциации, даже у вас есть has_many :through ассоциации следующим joins(.joins(insurance_subscriber_types: :insurance_subscribers_types_carriers).

вы получите SQL выхода следующим образом:

InsuranceSubscriber Load (3.3ms) SELECT "insurance_subscribers".* FROM 
"insurance_subscribers" INNER JOIN "insurance_subscriber_types" ON 
"insurance_subscriber_types"."insurance_subscriber_id" = 
"insurance_subscribers"."id" INNER JOIN "insurance_subscribers_types_carriers" ON 
"insurance_subscribers_types_carriers"."insurance_subscriber_type_id" = 
"insurance_subscriber_types"."id" WHERE (insurance_subscribers_types_carriers.status = 1) 

Я реплицируется и проверил вопрос со структурой модели, подобное этим:

PS: Я сделал небольшие изменения в ваших названиях моделей, так быть осторожен. Они были настолько запутанными, чтобы упростить их.

insurance_subscriber.гь

# == Schema Information 
# 
# Table name: insurance_subscribers 
# 
# id   :integer   not null, primary key 
# name  :string 
# status  :integer   default("0") 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# 

class InsuranceSubscriber < ActiveRecord::Base 
    has_many :insurance_subscriber_types, dependent: :destroy 
    has_many :insurance_types, through: :insurance_subscriber_types 
    has_many :insurance_subscribers_types_carriers, through:  :insurance_subscriber_types 

    enum status: {active: 0, passive: 1} 
end 

insurance_subscriber_types.rb

# == Schema Information 
# 
# Table name: insurance_subscriber_types 
# 
# id      :integer   not null, primary key 
# name     :string 
# insurance_subscriber_id :integer 
# insurance_type_id  :integer 
# created_at    :datetime   not null 
# updated_at    :datetime   not null 
# 

class InsuranceSubscriberType < ActiveRecord::Base 
    belongs_to :insurance_subscriber 
    belongs_to :insurance_type 

    has_many :insurance_subscribers_types_carriers, dependent: :destroy 
    has_many :carriers, through: :insurance_subscribers_types_carriers 
end 

insurance_subscribers_types_carriers.rb

# == Schema Information 
# 
# Table name: insurance_subscribers_types_carriers 
# 
# id       :integer   not null, primary key 
# carrier_id     :integer 
# insurance_subscriber_type_id :integer 
# status      :integer   default("0") 
# created_at     :datetime   not null 
# updated_at     :datetime   not null 
# 

class InsuranceSubscribersTypesCarrier < ActiveRecord::Base 
    belongs_to :carrier 
    belongs_to :insurance_subscriber_type 

    enum status: {active: 0, passive: 1} 
end 

insurance_types.rb

# == Schema Information 
# 
# Table name: insurance_types 
# 
# id   :integer   not null, primary key 
# name  :string 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# 

class InsuranceType < ActiveRecord::Base 
    has_many :insurance_subscribers_types_carriers 
    has_many :insurance_subscribers_types_carriers 
    has_many :insurance_subscribers, through: :insurance_subscribers_types 
end 
+0

Спасибо за помощь:)) – SpunkyLive

0

Если вы хотите использовать прилагаемую ассоциацию (insurance_subscribers_types_carriers) в запросе, вы должны добавить «ссылку» в противном случае insurance_subscribers_types_carriers будет загружаться отдельно от основного запроса:

InsuranceSubscriber.includes(:insurance_subscribers_types_carriers) 
       .where("insurance_subscribers_types_carriers.status = ?", 1) 
       .references(:insurance_subscribers_types_carriers) 
+0

Я сделал это уже, но это не соответствует моим требованиям. – SpunkyLive

Смежные вопросы