Hi everyone!
I’m a little bit new to Rails development and I am looking for a solution for this issue.
Let’s say that I have a model called Person and the person has an attribute name. But I want to put a surname with this name. Something like this:
class Unit < ActiveRecord::Base
def name= name
@name = name + ‘bla bla’
end
end
In Ruby I could do this, but this doesn’t affect my object at all…
How can I do that?
Thanks in advance
class Unit < ActiveRecord::Base
def name= name
@name = name + 'bla bla'
end
end
In Ruby I could do this, but this doesn't affect my object at all...
The key thing is that ActiveRecord attributes aren't instance
variables. You can use write_attribute to write to the store of
attributes.
Fred
So you would do
def name= name
write_attribute :name, name
end
class Unit < ActiveRecord::Base
def name= name
@name = name + 'bla bla'
end
end
In Ruby I could do this, but this doesn’t affect my object at all…
The key thing is that ActiveRecord attributes aren’t instance
variables. You can use write_attribute to write to the store of
attributes.
“This method is deprecated on the latest stable version of Rails. The last existing version (v1.2.6) is shown here.”
http://apidock.com/rails/ActiveRecord/Base/write_attribute
I’m sure I’ve seen it in later versions, but thought I’d post it anyway.
If it is deprecated, another way is:
self.attributes[‘name’] = name + ‘blah blah’
It’s not exactly the same as write_attribute (it doesn’t typecast to numbers for numeric columns) but it will work the same in your case.
Cheers,
Andy
I'm sure I've seen it in later versions, but thought I'd post it anyway.
If it is deprecated, another way is:
self.attributes['name'] = name + 'blah blah'
It's not exactly the same as write_attribute (it doesn't typecast to numbers
for numeric columns) but it will work the same in your case.
actually it is the same: active_record/base.rb says (in 2.3.5)
def =(attr_name, value)
write_attribute(attr_name, value)
end
Couldn't see any trace in the source of write attribute being marked
as deprecated.
Fred
Joe_Smith
(Joe Smith)
April 9, 2010, 2:05am
6
:Frederick Cheung:
Couldn't see any trace in the source of write attribute being marked
as deprecated.
It (ActiveRecord::Base#write_attribute) is not just deperecated, it is gone. But another method with the same name in a different class (ActiveRecord::AttributeMethods#write_attribute) replaced it. The new function has the same functionality and is in scope virtually everywhere the old one was. Thus to the end user, it is just the same as it has always been.
In other words the function moved.
Ahh OK, useful to know.
It would be helpful (in languages/frameworks in general) if a deprecation always had a comment on where to look for more information.
Generally Rails is good at this, but maybe that information isn’t filtered through to APIDock.com .
Cheers,
Andy