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

发布于 2024-10-17 06:39:39 字数 294 浏览 5 评论 0原文

我的模型中有以下方法

def reset_review_status
   needs_review = true
   save
end

模型上有一个名为 need_review 的属性,但是当我调试它时,它将它保存为新变量。如果我这样做 self.needs_review=true,它就可以正常工作。我没有 attr_accessible 子句,尽管我有一个accepts_nested_attributes_for。

对于为什么会发生这种情况有什么想法吗?

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. If I do self.needs_review=true, it works fine. I have no attr_accessible clause, although I do have one accepts_nested_attributes_for.

Any thoughts on why this might be happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

︶葆Ⅱㄣ 2024-10-24 06:39:39

当您在 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

根据经验:

  1. 当您想在方法中调用 setter 时,请始终使用 self.method_name =
  2. ;当存在同名的局部变量时,可以选择使用 self.method_name 。在上下文中

When you define an attribute in ActiveRecord, the following methods are available

# 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

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.

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
  2. optionally use self.method_name when a local variable with the same name exists in the context
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文