用户可以将多个预定义的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.id
和self.user_id
,会给我刚刚保存到DB的记录的id
和user_id
吗
如果没有为用户定义user_events,则带有print语句的行看起来会中断。。。添加一个if语句使其工作。。
print "total new events:" + self.user_events.size if user_events