0

我有三个模型定义如下

class Student < ActiveRecord::Base
  belongs_to :user
  has_many :placements
  has_many :companys , through: :placements
end

class Company < ActiveRecord::Base
    has_many :placements
    has_many :students , through: :placements
end

class Placement < ActiveRecord::Base
  belongs_to :student
  belongs_to :company

  before_save  :set_placed

  def set_placed
    s = self.student
    s.is_placed = true
    s.save
  end
end

每次我为放置对象添加数据时,我都想更新其相应学生对象中的字段。但是当我使用 rails_admin 添加数据时,我收到错误 Placement failed to be created 。

当我删除 before_save 调用时,可以添加数据。

我正在使用 better_errors gem 进行调试。我从中得到以下信息

@_already_called    

{[:autosave_associated_records_for_student, :student]=>false, 
 [:autosave_associated_records_for_company, :company]=>false}

我希望这可能是错误的原因。

我该如何解决这个错误?

4

2 回答 2

1

You have a s.save in your set_placed callback. You don't save an ActiveRecord object in a callback, and especially not in a before_save callback.

于 2013-10-28T12:56:13.957 回答
0

尝试这个,

def set_placed
  self.student.is_placed = true
end
于 2013-10-28T14:18:10.780 回答