简体   繁体   English

从Rails中的Model对象中调用访问器方法

[英]Calling accessor methods from within a Model object in Rails

I have the following method in my model 我的模型中有以下方法

def reset_review_status
   needs_review = true
   save
end

There is an attribute on the model called needs_review, however when I debug it, it saves it as a new variable. 模型上有一个名为needs_review的属性,但是当我调试它时,它会将其保存为新变量。 If I do self.needs_review=true , it works fine. 如果我做self.needs_review=true ,它工作正常。 I have no attr_accessible clause, although I do have one accepts_nested_attributes_for. 我没有attr_accessible子句,虽然我有一个accepts_nested_attributes_for。

Any thoughts on why this might be happening? 有关为什么会发生这种情况的任何想法?

When you define an attribute in ActiveRecord, the following methods are available 在ActiveRecord中定义属性时,可以使用以下方法

# gets the value for needs_review
def needs_review
end

# sets the value for needs_review
def needs_review=(value)
end

You can call the setter using 你可以使用调用setter

needs_review = "hello"

but this is the same way you set a variable. 但这与设置变量的方式相同。 When you call the statement within a method, Ruby gives higher precedence to variables assignment, thus a variable with that name will be created. 当您在方法中调用语句时,Ruby会为变量赋值提供更高的优先级,因此将创建具有该名称的变量。

def one
# variable needs_review created with value foo
needs_review = "foo"
needs_review
end

one
# => returns the value of the variable

def two
needs_review
end

two
# => returns the value of the method needs_review
# because no variable needs_review exists in the context
# of the method

As a rule of thumb: 根据经验:

  1. always use self.method_name = when you want to call the setter within a method 当你想在方法中调用setter时,总是使用self.method_name =
  2. optionally use self.method_name when a local variable with the same name exists in the context 当上下文中存在具有相同名称的本地变量时,可以选择使用self.method_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM