Cannot assign ActiveRecord Attributes in Model

南楼画角 提交于 2019-12-11 19:29:32

问题


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

For instance, I have an AccountModel and this has an Attribute 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

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.

Best regards, Mandi


回答1:


Try:

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.

You might want to save your changes after

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 ;)




回答2:


Your code looks fine, but are you saving the changes? Try adding a save call:

def set_name(new_name)
  self.name = new_name
  self.save
end



回答3:


Try

    def set_name(new_name)
      self.name = new_name
      self.save!
    end

Then call the instance method from controller simply

user.set_name('foo')



回答4:


You don't need to do self.save, just call save inside your model. You only use self.attribute when you need to assign.



来源:https://stackoverflow.com/questions/17991600/cannot-assign-activerecord-attributes-in-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!