Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 从Rails中的模型对象内调用访问器方法_Ruby On Rails_Ruby_Model_Attr Accessible - Fatal编程技术网

Ruby on rails 从Rails中的模型对象内调用访问器方法

Ruby on rails 从Rails中的模型对象内调用访问器方法,ruby-on-rails,ruby,model,attr-accessible,Ruby On Rails,Ruby,Model,Attr Accessible,我的模型中有以下方法 def reset_review_status needs_review = true save end 模型上有一个名为needs_review的属性,但是当我调试它时,它会将其保存为一个新变量。如果我做了self.needs\u review=true,它可以正常工作。我没有attr\u accessible子句,尽管我有一个接受嵌套属性的子句 有没有想过为什么会发生这种情况?在ActiveRecord中定义属性时,可以使用以下方法 # gets the

我的模型中有以下方法

def reset_review_status
   needs_review = true
   save
end
模型上有一个名为needs_review的属性,但是当我调试它时,它会将其保存为一个新变量。如果我做了self.needs\u review=true,它可以正常工作。我没有attr\u accessible子句,尽管我有一个接受嵌套属性的子句


有没有想过为什么会发生这种情况?

在ActiveRecord中定义属性时,可以使用以下方法

# gets the value for needs_review
def needs_review
end

# sets the value for needs_review
def needs_review=(value)
end
您可以使用

needs_review = "hello"
但这与设置变量的方式相同。在方法中调用语句时,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
根据经验:

  • 要在方法中调用setter时,请始终使用
    self.method\u name=
  • 当上下文中存在同名的局部变量时,可以选择使用
    self.method\u name