我什么时候需要在Mongoid中调用self.field =?

时间:2014-08-11 17:07:30

标签: ruby-on-rails ruby mongoid

我试图找到答案,但我的Google-fu必须生锈,否则所涉及的关键字会让结果非常嘈杂。

我的理解是,在Mongoid中声明一个字段会为该字段创建存取方法(即fieldfield=)。

我不清楚的是,由于用法似乎在各处混合使用,是否和/或何时需要调用self.field=来分配值,以及何时保存。< / p>

示例代码:

class Product
  field state, type: String, default: "inactive"
  field sku, type: String

  def active?
    state == 'active'
  end

  def inactive?
    !active?
  end
end

很明显,我可以在不调用self的情况下读取Mongoid字段定义的值。

但是如果我想在字段中写一个值,我是否需要调用self?即。

# any difference between these?
def activate
  state = 'active'
end
def activate
  self.state = 'active'
end

TIA。这看起来非常基本,但对于我的生活,我找不到明确的答案。

2 个答案:

答案 0 :(得分:4)

当您为实例的属性赋值时,您需要使用self.,否则会创建一个新的局部变量,在这种情况下state一旦超出范围就会被删除(方法结束)。在读取属性时,它会在当前范围内查找,然后在树上向上移动,在这种情况下,在实例上查找state

答案 1 :(得分:0)

查看以下可能有用的代码

class Product
  field state, type: String, default: "inactive"

  def activate
    p state #=> inactive
    p self.state #=> inactive
    state = 'active'
    p state #=> active
    p self.state #=> active

    # NOTE
    # in this example there is no difference between the 2... both refer to
    # the Product state field
  end

  def activate_state(state = 1)
    p state #=> 1
    p self.state #=> inactive
    state = 2
    self.state = 'active'
    p state #=> 2
    p self.state #=> active

    # NOTE
    # in this example there is a difference between the 2
    # cause in the scope of this method (activate_state) you have 2 state variables
    # and to distinguish between those 2 :
    # If you used self.state < you are referring to the Product.state field
    # If you used state < you are referring to the variable named state in the method
  end
end