Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

What I'm trying to do is display the data from Postgres in the table. Data is stored in Postgres in JSON format, db looks more or less like:

| id | data                 | created_at | updated_at |
|----|----------------------|------------|------------|
| 1  | [{"some_data": 90... | 2014-12-02 | 2014-12-02 |
| 2  | [{"some_data": 16... | 2014-12-03 | 2014-12-03 |
| 3  | [{"some_data": 38... | 2014-12-04 | 2014-12-04 |

for the quick hack I loaded the data column to @data like:

def index
  @data = Hack.pluck(:data).last
end

and then in views I would do:

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
  <% @data.each do |d|%>
    <tr>
      <th><%= d["some_data"][0] %></th>
      <th><%= d["some_data"][1]["name"]</th>
    </tr>
  <% end %>
  </tbody>
</table>

the problem is I end up with huge "variables" (d["some_data"][1]["name"]), plus if I would like to do some calculations I know it shouldn't be handled in views.

What is the best in RoR to accomplish that? I imagine I would have something like:

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
  <% @data.each do |d|%>
    <tr>
      <th><%= d.id %></th>
      <th><%= d.name %></th>
    </tr>
  <% end %>
  </tbody>
</table>
share|improve this question
    
Why aren't you just use normal relationship model? Rails and PostgreSQL doing this really great. If you thinking flat database model is better consider using MongoDB (or something like that). I don't see also any logical reason to store array as primary structure as record type. Is this some sort of cache? If so I think Redis will be better solution. – Eraden Jan 24 at 16:14
    
db is something "given" to me, can't change it, I agree with your point – knowbody Jan 24 at 16:15
    
If everything is stored in one table and in one column you simply cannot filter this. If any record will be too large, it will hit database performance and rails performance. You can stop rendering in some point and paginate this manually by skipping to point you need but this is just avoiding the real problem. You can also send this as JSON to browser and browser will render this (Backbone etc.). – Eraden Jan 24 at 16:28
    
Then what is a point of having JSON fields in postgresql? – knowbody Jan 24 at 21:50
    
To handle custom data for object. You can even filter rows by those data, but you cannot choose which data from this field should be taken and how many, when this is array. JSON, JSONB and HStore data types are also almost 2 times slower so I suggest to avoid them if possible. – Eraden Jan 25 at 11:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.