什么时候在模型中使用 self ? [英] When to use self in Model?

查看:50
本文介绍了什么时候在模型中使用 self ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我什么时候需要在 Rails 的模型中使用 self?

Question: when do I need to use self in my models in Rails?

我的一个模型中有一个 set 方法.

I have a set method in one of my models.

class SomeData < ActiveRecord::Base
  def set_active_flag(val)
    self.active_flag = val
    self.save!
  end
end

当我这样做时,一切正常.但是,当我这样做时:

When I do this, everything works fine. However, when I do this:

class SomeData < ActiveRecord::Base
  def set_active_flag(val)
    active_flag = val
    save!
  end
end

active_flag 值不会改变,而是静默失败.有人可以解释一下吗?

The active_flag value doesn't change, rather it fails silently. Can someone explain?

我找不到任何重复项,但如果有人找到也没关系.

I can't find any duplicates, but if someone finds one that's fine too.

推荐答案

当您对调用该方法的实例执行操作时,您使用 self.

When you're doing an action on the instance that's calling the method, you use self.

使用此代码

class SocialData < ActiveRecord::Base
  def set_active_flag(val)
    active_flag = val
    save!
  end
end

您正在定义一个名为 active_flag 的全新范围​​局部变量,将其设置为传入的值,它与任何内容都没有关联,因此当方法结束时它会被立即丢弃,就像它从未存在过一样.

You are defining a brand new scoped local variable called active_flag, setting it to the passed in value, it's not associated with anything, so it's promptly thrown away when the method ends like it never existed.

self.active_flag = val

然而告诉实例修改它自己的名为 active_flag 的属性,而不是一个全新的变量.这就是它起作用的原因.

However tells the instance to modify its own attribute called active_flag, instead of a brand new variable. That's why it works.

这篇关于什么时候在模型中使用 self ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆