ruby on rails 3-如何在ActiveRecord模型中存储要在回调中使用的数据



用户可以将多个预定义的events分配给一个room,但有时他们可能会动态创建新的events

我想捕获这些新事件,并将它们添加到单独的表userevent

下面是我的方法。我试图将所有不存在的事件保存到:user_events中,然后在after_save上回调add_new_events_to_userevents

  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_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]
      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

我收到一个错误

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
  • 如何存储所有新用户事件,然后在after_save回调中使用它们
  • after_save回调中,如果我调用self.idself.user_id,会给我刚刚保存到DB的记录的iduser_id

如果没有为用户定义user_events,则带有print语句的行看起来会中断。。。添加一个if语句使其工作。。

print "total new events:" + self.user_events.size   if user_events

相关内容

  • 没有找到相关文章

最新更新