Rails class User < ActiveRecord::Base ,这种类里面,为什么不能直接访问变量?

lin_style · June 26, 2012 · Last by jjym replied at June 26, 2012 · 2495 hits

假设 users 的表里有 count 这个字段,那么加函数

class User < ActiveRecord::Base
   def add_count()
      count+=1
   end
end

外面调用

user.add_count()

提示 count 找不到,但是 user.count 这样访问又是正常的。为啥??

因为 count +=1 就是 count = count + 1, 这时你其实想做的是 self.count = self.count + 1 count 为左值时,优先判断为函数内部变量,必须加上 self。 记得有个帖子对这个讨论的很仔细的。

#1 楼 @heliang7 多谢。。虽然不知道为什么,只是觉得 RUBY 对上下文看得很重。

#2 楼 @lin_style 因为要根据上下文做词法分析吧

You need to Sign in before reply, if you don't have an account, please Sign up first.