RubyOnRails Извлекать информацию из базы данных - PullRequest
0 голосов
/ 17 мая 2018

Какой запрос к базе данных мне нужно отправить, чтобы получить таблицу такого типа:

- название лекарства ----- Saller 1 ----- Saller 2 ----- Saller 3

- препарат 1 ------------ цена 1 ------- цена 2 ------ цена 3

- препарат 2 ------------- цена 4 ------- цена 5 ------- цена 6

Есть следующие модели: Таблица с наркотиками имеет названия лекарств

class Drug < ApplicationRecord
  has_many :drug_pharmacies     
  has_many :pharmacies, through: :drug_pharmacies 
end

В аптечном столе есть названия аптек

class Pharmacy < ApplicationRecord
    has_many :drug_pharmacies
    has_many :drugs, through: :drug_pharmacies
end

В таблице DrugPharmacies есть Drug_id, Pharmacy_id, цена

class DrugPharmacy < ApplicationRecord
    belongs_to :drug
    belongs_to :pharmacy
end

В списке контроллеров аптек (продавцов) я сформировал такой запрос (логика в поиске конкурентов, которые расположены рядом с основной аптекой по геолокации)

pharmacy= Pharmacy.find(params[:id])
longitude = pharmacy.x
latitude = pharmacy.y
@competitors = Pharmacy.where(x: (longitude-0.005..longitude+0.005), y: (latitude-0.005..latitude+0.005))

В тот же контроллер отправляю информацию о лекарствах

@drugs = Drug.all.sort_by &:name

И с такими запросами мне нужно перейти в базу данных для просмотра:

<table>
  <tr>
    <th>names</th> 
    <% @competitors.each do |apteka| %>        #filling the table with sellers
      <th><%= apteka.name %></th>
    <% end %>
  </tr>
                              #filling the table body with drugs and prices from competitors
  <% @drugs.each do |drug| %>
    <tr>
      <td><%= drug.name %></td>
      <% @competitors.length.times do |i| %>    #The problem in the presentation here is I suppose
        <td> <%= drug.drug_pharmacies.find_by_pharmacy_id(@competitors[i].id).price %> 
        </td>
      <% end %>
    </tr>
  <% end %>
</table>

1 Ответ

0 голосов
/ 22 мая 2018

Ответ был:

pharmacy= Pharmacy.find(params[:id])
longitude, latitude = pharmacy.x, pharmacy.y
@competitors = Pharmacy.where(x: (longitude-0.005..longitude+0.005),
                              y: (latitude-0.005..latitude+0.005))

В @competitors мы нашли наших соперников на площади. И тогда использование func включает в себя:

@drugs = Drug
            .includes(:drug_pharmacies)
            .where(drug_pharmacies: {pharmacy_id: @competitors.ids})

Здесь собраны все названия лекарств с ценами для всех ваших конкурентов.

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