Sebastian Thomas
Sebastian Thomas

Reputation: 148

Failing to save attributes of associated object in rails application

I have three models defined as follows

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

Each time i add data for placement object i want to update a field in its corresponding student object. But when i use rails_admin to add data , i am getting the error Placement failed to be created .

When i remove the before_save call , data can be added.

I am using better_errors gem for debugging. I am getting the following from it

@_already_called    

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

i am hoping this could be the reason for error.

How can i solve this error??

Upvotes: 0

Views: 100

Answers (2)

Brock90
Brock90

Reputation: 814

try this,

def set_placed
  self.student.is_placed = true
end

Upvotes: 0

eugen
eugen

Reputation: 9226

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.

Upvotes: 1

Related Questions