本文介绍了无法分配的ActiveRecord的模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想赋值我的模型中ActiveRecord的属性,但是由于各种原因,我不能将它们设置。

I am trying to assign values of ActiveRecord attributes within my models, but for whatever reason, I can't set them.

例如,我有一个AccountModel,这有一个属性名称

For instance, I have an AccountModel and this has an Attribute name

如果我从控制器或控制台设置(如 user.name =约翰),一切工作正常。但是,如果我尝试从模型中设置它,就像

If I set it from the controller or the console (like user.name = "John"), everything works fine.But, if I try to set it from within the model, like

def set_name(new_name)
  name = new_name
end

那么这是行不通的。另一方面,检索的名称,如

then it doesn't work. On the other hand, retrieving the name, like

def get_name
  name
end

工作得很好。我失去了一些东西?我使用Ruby 2.0.0-P247和Rails 4.0.0;请注意,这样的例子并不现实世界的例子,我只是试图让他们简单的澄清我的问题。

works just fine. Am I missing something?!I am using Ruby 2.0.0-p247 and Rails 4.0.0; Please note, that this examples aren't real world examples, I just tried to keep them simple to clarify my problem.

最好的问候,曼迪

推荐答案

尝试:

def set_name(new_name)
  self.name = new_name
end

您需要使用关键字来引用在分配给您的实例属性。否则红宝石将指定新的名字一个叫名称

You need to use the self keyword to refer to your instance attributes on assignment. Otherwise ruby will assign your new name to a local variable called name.

您可能希望保存

user = User.new
user.set_name('foo')
user.save

看看这个例子这里,有一个类似于您在最后的问题;)

Take a look at the example here, there is one similar to your question at the end ;)

这篇关于无法分配的ActiveRecord的模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:47