[Rails] Re: why do I have to refer to my attr_accessible as self.varname?
Frederick Cheung wrote in post #1089897:
>
> Because rails doesn't use individual instance variables to store your
> attributes (whether they've been marked as attr_accessible makes no
> difference)
>
> title = "foo"
>
> Doesn't work because ruby assumes that you want to assign to the local
> variable called title. Doing self.title = makes it clear that you want
> to call the title= accessor
>
While true, that has nothing to do with the op's problem--the op is
assigning to an @ variable, and an @ variable, like @title, can never be
a local variable. There is only one way for ruby to interpret an
assignment like:
@title = some_value
>Is there typically a standard way of doing things?
Yes. Always use the accessor method to set or get the value of an
instance variable. Here is an example of how things can go wrong:
class Dog
def title=(val)
@title = val.capitalize
end
def do_stuff
@title = "mr."
@title + " Dog"
end
end
puts Dog.new.do_stuff
--output:--
mr. Dog
And here is how to correct the problem:
class Dog
def title=(val)
@title = val.capitalize
end
def do_stuff
self.title = "mr."
@title + " Dog"
end
end
puts Dog.new.do_stuff
What you did is bypass an accessor method, which you did not define and
therefore are blissfully unaware of what it does, and your results
showed that the accessor method did something critical.
--
Posted via http://www.ruby-forum.com/.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home