after_create回调似乎无法正常工作

时间:2012-02-16 04:57:17

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有以下代码和日志信息。 global_id值设置为attr_accessible

这个有效

代码:

Location.update(model[:id],:global_id => gi[:id])

日志

before location save
  Location Load (0.3ms)  SELECT `locations`.* FROM `locations` WHERE `locations`.`id` = 280 LIMIT 1
 (0.3ms)  UPDATE `locations` SET `global_id` = 11490, `updated_at` = '2012-02-16 04:48:17' WHERE `locations`.`id` = 280
after location save

这个没有,我不知道为什么。任何想法:

代码:

User.update(model[:id],:global_id => gi[:id])

日志:

here is more info
 here i am and I am a user
 User Load (0.3ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 31 LIMIT 1
  (0.3ms)  SELECT 1 FROM `users` WHERE (`users`.`email` = BINARY 'jj@jxx.com' AND `users`.`id` != 31) LIMIT 1
after my user update

为什么第二个不起作用的任何想法?

THX

编辑#1 两种模型都有:

after_create SaveGlobalInfo

该课程为:

class SaveGlobalInfo < ActiveRecord::Base
  def self.after_create(model)
    gi=GlobalIdentification.create()
    if (model.class.name=='Location')
      puts "before location save"
      Location.update(model[:id],:global_id => gi[:id])
      puts "after location save"
    elsif (model.class.name=='User')
      puts "here i am and I am a user"
      User.update(model[:id],:global_id => gi[:id])
      puts "after my user update"
    end

1 个答案:

答案 0 :(得分:3)

如果我不得不猜测是因为你没有通过某种验证。使用第二个SQL调用执行的测试是为了确保email字段的唯一性。如果失败并且无法保存记录怎么办?

这特别奇怪:

after_create SaveGlobalInfo

您可以为回调创建辅助类,但我以前从未将它们视为实际的ActiveRecord模型。也许你的意思是定义一个模块?