开发者

how to store data to be used in the callback in ActiveRecord model

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
      u.save
    end
  end

  def event_tokens=(ids)
    events = ids.split(',')
    allowed_ev开发者_运维知识库ents = []
    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]
      else
        userevents << i
      end
    end
    self.event_ids = allowed_events #these are events that exist
    self.user_events = userevents #these are new events, need them in after_save
  end

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜