Rails:从模型方法访问字段值 [英] Rails: accessing field value from model method

查看:87
本文介绍了Rails:从模型方法访问字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始学习Rails(3).我正在努力寻找可能做的琐碎的事:从模型实例的方法内部访问模型实例的字段的值.

Just started learning 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.

就我而言:

def formal_name
  @title + " " + @forename + " " + @surname
end

所有三个@properties(它们是数据库表中的所有字段)都返回nil.他们不应该.

All three @properties (which are all fields on the table in the database) return nil. They shouldn't.

令人难以置信的是, http://guides.rails.info/上没有讨论如何访问字段. ,而Google却一无所获.

Incredibly, how to access fields isn't discussed at http://guides.rails.info/, and google turns up nothing.

顺便说一句,我来自Django,那里的东西很明显.

BTW, I'm coming from Django where this stuff is obvious.

推荐答案

@语法用于实例变量,例如,实例变量在控制器中填充,然后在视图中使用.不是你在这里做什么.

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.

您实际上只需要

def formal_name
  title + " " + forename + " " + surname
end

这篇关于Rails:从模型方法访问字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆