I’m trying to figure out why both ‘self.name’ and ‘name’ work in a
model class. For example:
class Category < ActiveRecord::Base
before_save :set_permalink
private
def set_permalink
# both work
self.permalink = name
self.permalink = self.name
# doesn’t work
permalink = name @permalink = name @permalink = @name
self.permalink = @name
end
end
I thought that attributes in a class were set via instance methods,
but ‘self.permalink = @name’ doesn’t work, but ‘name’ (which looks
like a local variable to me) works fine. And self.permalink works, but @permalink doesn’t.
I’m still new to Ruby and classes so it’s probably something simple I
don’t understand, so any help would be appreciated.
Basically name and self.name are interpreted by ruby as methods…
because your model when mapped to its corresponding table has a
column called ‘name’, rails creates the relevant method instance.name.
Therefore your reference to name and self.name are calling the same
method… as name (without the self.) is scoped to the instance method
(as its inside an instance method itself), and self evaluates to the
instance, therefore it calls the instance method ‘name’…
both work
self.permalink = name <-- calls method name, and its value is
passed to the method ‘permalink’ (again, not an variable really)
self.permalink = self.name <-- calls same method… as self.
evaluates to the instance
# doesn’t work
permalink = name <-- ruby is probably getting confused here…
which is probably why its not working… @permalink = name <-- again this is probably being set … but it
wont update your model as it is saved… because @permalink is a var
self.permalink is the method you need to call to update your model… @permalink = @name <— again they are not instance vars. … so @permalink => nil but you wont see it in your db…
self.permalink = @name <-- @name doesnt exist … so will be nil…
I hope that makes sense… sunday afternoon in the office has left my
brain a bit fried… (mainly because im writing actionscript…)
Good luck!
Jason.
On 1 Jul 2007, at 17:10, rob wrote:
I’m trying to figure out why both ‘self.name’ and ‘name’ work in a
model class. For example:
class Category < ActiveRecord::Base
before_save :set_permalink
private
def set_permalink
# both work
self.permalink = name
self.permalink = self.name
# doesn’t work
permalink = name @permalink = name @permalink = @name
self.permalink = @name
end
end
I thought that attributes in a class were set via instance methods,
but ‘self.permalink = @name’ doesn’t work, but ‘name’ (which looks
like a local variable to me) works fine. And self.permalink works, but @permalink doesn’t.
I’m still new to Ruby and classes so it’s probably something simple I
don’t understand, so any help would be appreciated.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.