Rails:after_create期间的问题

时间:2013-06-02 23:41:30

标签: ruby-on-rails rails-activerecord self-join before-filter

我制作了一个相对复杂的填字游戏解决方案Rails应用程序,但这个问题只涉及其两个相互作用的模型:Crossword和Cell。

计划:

在创建填字游戏之前,我填充了一些等于其(行*列)的单元格。然后,在为该拼图填充所有单元格之后,每个单元格与其相邻的单元格相关联。

这是Cell类的删节版本。请注意,每个单元格与其相邻单元格具有倒数关联,由.assign_bordering_cells方法设置。

class Cell < ActiveRecord::Base

  ....

  has_one :right_cell, class_name: 'Cell', foreign_key: 'left_cell_id', inverse_of: :left_cell
  has_one :below_cell, class_name: 'Cell', foreign_key: 'above_cell_id', inverse_of: :above_cell
  belongs_to :left_cell, class_name: 'Cell', foreign_key: 'left_cell_id', inverse_of: :right_cell
  belongs_to :above_cell, class_name: 'Cell', foreign_key: 'above_cell_id', inverse_of: :below_cell

  def assign_bordering_cells!
    puts "Assign bordering cells for cell in row #{self.row}, column #{self.col}"
    self.left_cell = self.crossword.cells.find_by_row_and_col(self.row, self.col-1) unless (self.col == 1)
    self.above_cell = self.crossword.cells.find_by_row_and_col(self.row-1, self.col) unless (self.row == 1)
    self.save
  end
end

这是删节的填字游戏课程。填充单元格后,.link_cells方法遍历所有这些单元格,将它们链接到邻居。

class Crossword < ActiveRecord::Base
  before_create :populate_cells
  after_create :link_cells

  ...

  def populate_cells
    row = 1
    while (row <= self.rows)
      col = 1
      while (col <= self.cols)
        self.cells << Cell.new(row: row, col: col, is_across_start: col == 1, is_down_start: row == 1)
        col += 1
      end
      row += 1
    end
  end

  def link_cells
    self.cells.each {|cell| cell.assign_bordering_cells! }
  end

end

最终结果应该是每个细胞都知道&#34;哪个单元格位于其上方,下方,左侧和右侧。我已经解释了可能缺少1-2个这些邻接细胞的边缘细胞。

The Hitch:

当我使用新的填字游戏为我的数据库播种时,会为其正确创建单元格。但是,虽然.link_cells被明确调用,.assign_bordering_cells!每个单元格触发一次,但Cell-Cell关联不会被保存。

如果我在之后运行Crossword.first.link_cells 我已经播种了数据库,那么所有的Cell都会完美地连接起来。这是完全相同的过程,但是一个正在:after_create过滤器中发生,一个我在Rails控制台中输入。

问题: 在我创建了一个填字游戏之后,为什么.link_cells在Rails控制台中有效,而在我的:after_create过滤器对象过滤器中却没有?

0 个答案:

没有答案