получить записи из таблицы таблиц has_many? - PullRequest
0 голосов
/ 24 сентября 2019

У меня есть три модели с нижеприведенными ассоциациями: -

class Property < ApplicationRecord
  has_many :properties_room_type
  has_many :rate_plan_mappings, through: :properties_room_type
end

class PropertiesRoomType < ApplicationRecord
  has_many :rate_plan_mappings
  belongs_to :property
end

class RatePlanMapping < ApplicationRecord
  belongs_to :properties_room_type
end

У меня есть rate_plan_id в rate_plan_mappings таблица Итак, мой мотив - создать хеш как: -

{property_id => [rate_plan_id]} в качестве свойства has_many rate_plan_mappings}

example:

 {1 => [22,23], 2 => [25,29,30], 3 => [9,7,6]}

в качестве 1,2,3 являются property_id, а для массива - rate_plan_id, соответствующего ему.

Как я могу присоединиться к таблице и создать этот тип структуры из вышеупомянутой ассоциации.

Я могу сделать один в один с каждым циклом, но это не правильный метод: -

prop_hash = {}
prop_all = Property.all
prop_all.each do |property|
  prop_hash.merge!("#{property.id}" => [property.rate_plan_mappings.where(active: true).pluck(:rate_plan_id).uniq])
end

1 Ответ

1 голос
/ 24 сентября 2019

Вы можете попробовать следующее:

# query data
arr = RatePlanMapping.joins(properties_room_type: :property).pluck("properties.id", "rate_plan_mappings.rate_plan_id")

# Group arr by property_id
hash = arr.group_by { |sub_arr| sub_arr[0] }

# Modify Hash to desired structure
modified_hash = {}

hash.each do |k, arr|
  modified_hash[k] = [ arr.flatten.uniq - [ k ] ].flatten
end

Например, для

arr = [
  [2, 10],
  [2, 20],
  [1, 21],
  [2, 22],
  [3, 23]
]

, где arr[N][0] - это property_id, а arr[N][1] - это rate_plan_id, modified_hash должен держать {2=>[10, 20, 22], 1=>[21], 3=>[23]}

Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...