Charlie May
Charlie May

Reputation: 112

Activerecord callback to modify associated model

I have 2 models with an association. I want to setup a before_save in one model to modify the other. Here is what I have:

class Event < ActiveRecord::Base
  belongs_to :leads
end

class Lead < ActiveRecord::Base
  before_save  :update_event
  has_many :events, :dependent => :destroy
  accepts_nested_attributes_for :events, :reject_if => lambda { |a| a[:title].blank? }

  def update_event
    self.events.title = "Testing to set the event title"
  end
end

Ultimately Event has attributes such as title that will be set from various model associations within the system. In the example above, Leads is one of them. Leads will have a drop-down list of possible events so I would want to do something in a before_save whereas the selection in the drop-down ends up setting the event title. such as:

self.events.title = self.selected_event

The error I get is the following:

undefined method `title=' for #<ActiveRecord::Relation:0x007fed3229d610>

I'm clearly doing this wrong. I'd appreciate any help at all. I'm still searching for a solution and will update this myself if I figure it out.

Thank you!

Upvotes: 0

Views: 386

Answers (1)

gylaz
gylaz

Reputation: 13571

You have multiple events per lead. So, in your situation you'd want to:

before_save  :update_events

def update_events
  events.each do |event|
    event.title = "Testing to set the event title"
  end
end

Upvotes: 2

Related Questions