在Rails的重写实例方法

在Rails的重写实例方法

本文介绍了在Rails的重写实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

虽然覆盖了一些分配方法,我发现,如果我使用隐式接收器的field_two方法,首先覆盖的方法,field_one,不会被调用。相反,默认的'field_one ='好像是叫。

While overriding some assignment methods, I discovered that if I use the implicit receiver in the field_two method, the first overridden method, field_one, doesn't get called. Instead, the default 'field_one=' seems to be called.

#controller
def do_something
  @something=Something.first
  @something.field_two="some_value"
end

class Something<ActiveRecord::Base

def field_one=(value)
  puts "hi"
  write_attribute(:field_g_five,value)
end


def field_two=(value)
  field_one="whatever"
  write_attribute(:field_g_one,value)
end

end

不过,如果我改变接收机是明确的,我重写的方法被调用:

However, if I change the receiver to be explicit, my overridden method gets called:

def field_two=(value)
  self.field_one="whatever"
  write_attribute(:field_g_one,value)
end

什么是怎么回事?

What is going on here?

推荐答案

默认 field_one 是没有得到所谓的,你设置了一个名为本地变量 field_one 里面的方法。

The default field_one isn't getting called, you're setting a local variable called field_one inside the method.

如果你想它明确要调用 field_one 那个类中的方法,您必须$与点$ PFIX它的自我

If you want to make it explicit that you want to call the field_one method inside that class, you must prefix it with self.

这篇关于在Rails的重写实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:45