infinity
infinity

Reputation: 719

Model to correspond to another model

I have a rails application where I have three models: Table, Column, and Row. They look like this:

Table:

has_many :columns
accepts_nested_attributes_for :columns

Column:

belongs_to :table
has_many :rows

accepts_nested_attributes_for :rows, :reject_if => lambda { |b| b[:data].blank? }

Row:

belongs_to :column

I'm trying to make a table like the one I described in a previous answer: Creating a spreadsheet. To implement it, I have two controllers: a TablesController, and a RowsController (The Rows Controller should probably be called something different because it contains both rows and columns). I have nested routes, so you can visit /tables/1/rows and it will show you the columns that are associated with the 1st table.

Here's the code:

@columns = Column.where(:table_id => @table.id)
@rows = Row.all

and:

<% @columns.each do |column| %>
  <% @rows.each do |row| %>
     Column name:<%= column.name %><br>
     Row data: <%= row.data %><br>
    <hr>
  <% end %>
<% end %>

As you can see, the rows are returning ALL of the results in the entire database. But I can't figure out how to get them to correspond to the column they are with?

Thanks for all help!

Upvotes: 0

Views: 43

Answers (1)

vee
vee

Reputation: 38645

Update your controller code from:

@columns = Column.where(:table_id => @table.id)
@rows = Row.all

to:

@columns = Column.where(:table_id => @table.id)

Then in your view:

<% @columns.each do |column| %>
  <% column.rows.each do |row| %>
     Column name:<%= column.name %><br>
     Row data: <%= row.data %><br>
    <hr />
  <% end %>
<% end %>

Because you have @rows = Rows.all, it is going to return all the rows in rows table. To retrieve rows for a particular column you would do column.rows.

Upvotes: 1

Related Questions