开发者

Generating column-based table in ruby on rails view

开发者 https://www.devze.com 2023-01-05 10:01 出处:网络
I need a bit help with dynamically generating column-based table instead of row-based table. Let\'s say that I have a hospital and hospital has many patients.

I need a bit help with dynamically generating column-based table instead of row-based table.

Let's say that I have a hospital and hospital has many patients.

Hospital no 1

          | Day 1 | Day 2 | Day 3     
Patient 1 | 36.6  | 36.4  | 36.5      
Patient 2 | 37.0  | 37.1  | 36.6      
Patient 3 | 37.1  | 36.4  | 36.7      
Patient 4 | 36.6  | 36.6  | 36.6      
Patient 5 | 36.7  | 37.1  | 36.4  

Each day, each patient has his body temperature checked. I would like to get a tip/hint or example of help dynamically drawing such table - adding new data vertically, not horizontally. Hopefully you get wh开发者_JS百科at i mean.

Thank you, in advance :)


I'm assuming you meant something like this:

you have three models:

class Hostpital < ActiveRecord::Base
  has_many :patients
  has_many :temp_readings, :through => :patients
end

class Patient < ActiveRecord::Base
  belongs_to :hospital
  has_many :temp_readings
end

class TempReading < ActiveRecord::Base
  belongs_to :patient
end

Than you can build a table in an erb view like this:

<table>
  <thead>
    <tr>
      <th>&nbsp;</th>
      <%- some_hospital.temp_readings.map(&:date_of_reading).sort do |date_of_reading| -%>
        <th><%= date_of_reading %></th>
      <%- end -%>
    </tr>
  </thead>
  <tbody>
    <%- some_hospital.patients.each do |patient| -%>
      <tr>
        <th><%= patient.name %></th>
        <%- patient.hospital.temp_readings.map(&:date_of_reading).sort do |date_of_reading| -%>
          <td><%= patient.temp_reading.find_by_date_of_reading(date_of_reading) %></td>
        <%- end -%>
      </tr>
    <%- end -%>
  </tbody>
</table>

I'm assuming you have some column with a date in your Reading Model, I just called it date_of_reading


If your question relates to the storage and representation of the data within your application then you can do this with 2 models as follows:

class Patient < ActiveRecord::Base
  has_many :temp_readings
end

class TempReading < ActiveRecord::Base
  belongs_to :patient
end

When creating a new reading for each patient you add a row to the temp_readings table. When displaying these readings (say for the last 7 days) you print the last 7 row values of temp_readings for each patient across a single line giving you the columnar output.

0

精彩评论

暂无评论...
验证码 换一张
取 消