Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails3Observer——希望了解如何为多个模型实现一个观察器_Ruby On Rails_Ruby On Rails 3 - Fatal编程技术网

Ruby on rails Rails3Observer——希望了解如何为多个模型实现一个观察器

Ruby on rails Rails3Observer——希望了解如何为多个模型实现一个观察器,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有以下观察员: class NewsFeedObserver < ActiveRecord::Observer observe :photo, :comment def after_create(record) end end 或者更容易想象: if record == 'Photo' 如何记录并确定型号名称 您需要为不同的模型设置不同的观察者 所以对于User=>UserObserver,Photo=>PhotoObserver 您需要告诉rails应用程序要使用哪些

我有以下观察员:

class NewsFeedObserver < ActiveRecord::Observer
  observe :photo, :comment

  def after_create(record)
  end
end
或者更容易想象:

if record == 'Photo'

如何记录并确定型号名称

您需要为不同的模型设置不同的观察者

所以对于User=>UserObserver,Photo=>PhotoObserver

您需要告诉rails应用程序要使用哪些观察者,这是您在config/environment.rb中指定的

至少这是标准的方法。欲知详情


您需要为不同的型号设置不同的观察者

所以对于User=>UserObserver,Photo=>PhotoObserver

您需要告诉rails应用程序要使用哪些观察者,这是您在config/environment.rb中指定的

至少这是标准的方法。欲知详情


在一篇评论中,我注意到您发现它使用的是
record.class.name
,但这不是非常地道的Ruby。Ruby
case
语句使用
=
进行比较,如果您正确实现它,这将非常适合您

class NewsFeedObserver < ActiveRecord::Observer
  observe :photo, :comment

  def after_create(record)
    case record
      when Photo
        # do photo stuff
      when Comment
        # do comment stuff
      else
        # do default stuff
    end
  end
end

我建议你注意以下几点:

class Sample
end

s = Sample.new

Foo === s   # true   uses Class#===
s === Foo   # false  uses Object#===

=
Class
Object
中的实现方式不同。在一篇评论中,我注意到您发现使用
record.Class.name
可以实现这一点,但这并不是非常惯用的Ruby。Ruby
case
语句使用
=
进行比较,如果您正确实现它,这将非常适合您

class NewsFeedObserver < ActiveRecord::Observer
  observe :photo, :comment

  def after_create(record)
    case record
      when Photo
        # do photo stuff
      when Comment
        # do comment stuff
      else
        # do default stuff
    end
  end
end

我建议你注意以下几点:

class Sample
end

s = Sample.new

Foo === s   # true   uses Class#===
s === Foo   # false  uses Object#===
==
类和
对象中的实现方式不同,这实际上是有效的。。。“record.class.name”如果能找到一种方法也能得到动作,那就太好了。。。创作,创作,等等…这确实有效。。。“record.class.name”如果能找到一种方法也能得到动作,那就太好了。。。创建、编辑等。。。