[英]Rails: accessing field value from model method
Just started learning Rails (3). 刚开始学习Rails(3)。 I am tearing my hair out trying to find how to do something presumably utterly trivial: access the value of a model instance's field, from inside a method on that model.
我正在试图找出如何做一些可能完全无关紧要的事情:从模型中的方法内部访问模型实例的字段的值。
In my case: 就我而言:
def formal_name
@title + " " + @forename + " " + @surname
end
All three @properties (which are all fields on the table in the database) return nil
. 所有三个@properties(数据库中表的所有字段)都返回
nil
。 They shouldn't. 他们不应该。
Incredibly, how to access fields isn't discussed at http://guides.rails.info/ , and google turns up nothing. 令人难以置信的是, http://guides.rails.info /中没有讨论如何访问字段,谷歌也没有任何内容。
BTW, I'm coming from Django where this stuff is obvious. 顺便说一句,我来自Django,这个东西很明显。
The @ syntax is used for instance variables that (for example) get populated in controllers and then used in views. @语法用于实例变量(例如)在控制器中填充,然后在视图中使用。 Not what you're doing here.
不是你在这里做的。
You actually just need 你其实只是需要
def formal_name
title + " " + forename + " " + surname
end
You have to omit the @, you access them via getter methods. 你必须省略@,你可以通过getter方法访问它们。 In some cases you must use
self.<field>
due to ambiguity. 在某些情况下,由于含糊不清,您必须使用
self.<field>
。
class MyModel << ActiveRecord
def formal_name
title = self.title # return title attribute of instance
forename = self.forename
surename = self.surname
# or something like this
self.title + self.surename
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.