4

我正在尝试在rails中构建一个网格来输入数据。它有行和列,行和列由单元格连接。在我看来,我需要网格能够处理边缘上的“新”行和列,这样如果您输入它们然后提交,它们会自动生成,并且它们的共享单元格正确连接到它们. 我希望能够在没有 JS 的情况下做到这一点。

Rails 嵌套属性无法处理映射到新记录和新列的问题,它们只能做其中一个。原因是它们是专门嵌套在两个模型之一中的,无论它们没有嵌套在哪个模型中,都没有 id(因为它还不存在),并且当通过顶级 Grid 模型上的accepts_nested_attributes_for 推送时,它们只会绑定到为它们嵌套的任何内容创建的新对象。

我该如何处理?我是否必须覆盖对嵌套属性的 Rails 处理?

我的模型看起来像这样,顺便说一句:

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
4

1 回答 1

0

就在几天前,我遇到了类似的问题,据我所知,双嵌套问题没有办法解决。通过改变我对问题的“心理”模型,我超越了它。在回顾我所做的并将其转化为您的情况时,这是我采取的方法:

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

  accepts_nested_attributes_for :cells, :allow_destroy => true
end

class Cell
  has_one column
  has_one row
  belongs_to grid
end

class Column
  has_and_belongs_to_many cells
end

class Row
  has_and_belongs_to_many cells
end

您将通过以下语句/方法获得一些您想要的功能:

a_row = Grid.cells.where("row_id = a_cell.row_id")

def remove  # an instance method for Row
   self.cells.each do |cell|
       cell.delete
   end
end

def add_column  # an instance method for Grid
    self.column_count += 1
    self.row_count.times do |i|
       cell.new(:column_id => :self.column_count, :row_id => :i)
       cell.save
    end
end

您要在网格上执行的许多面向列和行的操作将需要使用您编写的方法和范围来完成,以创建具有共同 row_id 或 column_id 的单元格集合。

不确定这是否完全适合您的情况,但它可能会帮助您使用一些不同的模型方法。祝你好运。

于 2012-04-04T06:22:52.867 回答