views:

208

answers:

0

I'm trying to build a grid, in rails, for entering data. It has rows and columns, and rows and columns are joined by cells. In my view, I need for the grid to be able to handle having 'new' rows and columns on the edge, so that if you type in them and then submit, they are automatically generated, and their shared cells are connected to them correctly. I want to be able to do this without JS.

Rails nested attributes fail to handle being mapped to both a new record and a new column, they can only do one or the other. The reason is that they are a nested specifically in one of the two models, and whichever one they aren't nested in will have no id (since it doesn't exist yet), and when pushed through accepts_nested_attributes_for on the top level Grid model, they will only be bound to the new object created for whatever they were nested in.

How can I handle this? Do I have to override rails handling of nested attributes?

My models look like this, btw:

class Grid < ActiveRecord::Base
  has_many   :rows
  has_many   :columns
  has_many   :cells, :through => :rows

  accepts_nested_attributes_for :rows,
    :allow_destroy => true,
    :reject_if => lambda {|a| a[:description].blank? }
  accepts_nested_attributes_for :columns,
    :allow_destroy => true,
    :reject_if => lambda {|a| a[:description].blank? }
 end


 class Column < ActiveRecord::Base
   belongs_to :grid
   has_many :cells, :dependent => :destroy
   has_many :rows, :through => :grid
 end

 class Row < ActiveRecord::Base
   belongs_to :grid
   has_many   :cells, :dependent => :destroy
   has_many   :columns, :through => :grid

   accepts_nested_attributes_for :cells
 end


 class Cell < ActiveRecord::Base
   belongs_to :row
   belongs_to :column
   has_one    :grid, :through => :row
 end