Reputation: 1456
I have method which is saving my session and event
def create_session
new_session = NewSession.new
new_session.transaction do
new_session.name = 'Somename'
....
new_session.save!
event = new_session.event #returning nil why?
puts event.new_session
end
end
My NewSession
class
class NewSession < ActiveRecord::Base
has_one :event, :class_name => SessionEvent, :dependent => :delete
after_create :create_event
def create_event
SessionEvent.create(:name => 'Eventname', :new_session => self)
end
end
Now How can I get associated object created using after_create callback in rails transaction
Upvotes: 1
Views: 2294
Reputation: 1394
after_create() -
Is called after Base.save on new objects that haven’t been saved yet (no record exists). Note that this callback is still wrapped in the transaction around save. For example, if you invoke an external indexer at this point it won’t see the changes in the database.
so I w'll suggest you to use after_save callback
Upvotes: 0
Reputation: 1191
Try to do this:
class NewSession < ActiveRecord::Base
has_one :event
after_create :create_event
def create_event
self.event.create(:name => 'Eventname')
end
end
But make sure that you have 'new_session_id' in your events table, if not then add it to events table or define foreign_key in you association as:
has_one :event, :foreign_key => "new_session"
and now use your own model code.
EDIT
Rather then save whole 'self' in event model you just save 'self.id' as:
def create_event
Event.create(:name => 'Eventname', :new_session => self.id)
end
And define you assoication as I suggested above has_one :event, :foreign_key => "new_session"
Hope this will help you.
Upvotes: 1
Reputation: 1601
Make sure that you have 'new_session_id' in your events table, then
class NewSession < ActiveRecord::Base
has_one :event
after_create :create_event
def create_event
self.event.create(:name => 'Eventname')
end
end
Upvotes: 0