RoR:创建方法后堆栈级别太深了?

时间:2011-03-10 12:22:15

标签: ruby-on-rails

在我的记录模型中创建方法后,我有以下内容,每当我尝试创建新记录时,它都会使堆栈级别过于错误:

class record

  has_many :authorizations
  has_many :roles, :through => :authorizations, :dependent => :destroy, :primary_key => :record_secondary_id

  after_create :new_record

  def create_roles
    self.roles.create :name => "#{self.record_title} edit", :record_id => self.id, :edit => true, :review => false
    self.roles.create :name => "#{self.record_title} review", :record_id => self.id, :edit => false, :review => true
  end

  def set_secondary_id
      self.update_attribute :record_secondary_id, self.id
  end

  def new_record
    if self.record_secondary_id.blank?
      set_secondary_id
      create_roles
    end
  end
  end

end

2 个答案:

答案 0 :(得分:1)

你在create record和create_roles之间有无限的递归。

您需要使用记录本身而不是回调来创建角色。 通过关系使用has_many会很容易。

编辑:

在你的控制器中,

@record = Record.new(params[:record])
@role1 = Role.new('some_params')
@role2 = Role.new('some_params')
@record.roles = [@role1, @role2]
@record.save

答案 1 :(得分:0)

我认为您的问题可能来自以下电话:

 has_many :authorizations
 has_many :roles, :through => :authorizations, :dependent => :destroy, :primary_key => :record_secondary_id

将其更改为:

  has_many :authorizations, :dependent => :destroy, :primary_key => :record_secondary_id
  has_many :roles, :through => :authorizations

应该解决你的问题。

相关问题