Take the 2-minute tour ×

user can assign multiple predefined events to a room however, sometimes they might create new events on the fly.

I want to capture these new events and add them to a separate table userevent

Below is my approach. I am trying to save all the events that don't exist into a :user_events and then callback add_new_events_to_userevents on after_save.

  after_save :add_new_events_to_userevents
  attr_reader :event_tokens, :user_events 
  attr_accessible :user_events #not real column in table
  attr_accessible :fulladdress, :title, :description, :cost, :email, :maximum_capacity, :phone, :user_id, :property_id

  def add_new_events_to_userevents
    print "total new events:" + self.user_events.size
    self.user_events.each do |i| 
      u = Userevent.new
      u.name = i
      u.approved = false
      u.room_id = self.id
      u.user_id = self.user_id

  def event_tokens=(ids)
    events = ids.split(',')
    allowed_events = []
    userevents = []
    events.each do |i|
      i = i.strip
      events = Event.select(:id).where("upper(name) = ?", i.upcase);
      event = (events.blank? ? nil : events.first)
      if event.present?
        allowed_events << event[:id]
        userevents << i
    self.event_ids = allowed_events #these are events that exist
    self.user_events = userevents #these are new events, need them in after_save

I am getting an error

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.size
  • how can I store all new user events and then use them in my after_save callback?
  • in the after_save callback if I call self.id and self.user_id will that give me id and user_id of the record that was just saved to the DB?
share|improve this question

1 Answer 1

up vote 0 down vote accepted

looks like the line with the print statement breaks if you don't have user_events defined for a user... add an if-statement to it to make it work..

print "total new events:" + self.user_events.size   if user_events
share|improve this answer
well that will fix the error however, I still can't get the user_events to get saved. –  Omnipresent May 30 '11 at 20:47
well, if you got the error about a nil object, that means that self.user_events was nil ... e.g. there are_no user_events for some other reason... can you double-check with a valid example where you know that there should be user_events defined for that user? –  Tilo May 30 '11 at 21:27
I've checked that. I wish to know whether the technique I am using (saving user_events in a self variable and then using that variable in after_save method is the best way to go –  Omnipresent May 31 '11 at 20:26
what is self? you didn't mention what the outer class is... –  Tilo Jun 2 '11 at 20:15

Your Answer


