TL;DR: The controller's are stateless, they just see the incoming request. To have a list outlive the current request, you need to persist the list in either the session or in the database, depending on how long you want it to live and other considerations.
There are some other issues...
Don't used defined?
for that, in fact, don't use defined?
for anything. It doesn't have many legit application-level uses. In this case, libraryshelf
is a local variable, and on its first reference in the method it will always not be defined.
Operate directly on @listofbooks
and just check @listofbooks or @listofbooks.nil?
.
Here are a few working (I think) versions...
def add_book name
@listofbooks = [] unless @listofbooks
@listofbooks << name
end
def add_book name
@listofbooks ||= []
@listofbooks << name
end
def add_book name
@listofbooks = @listofbooks.to_a.push name # yes, works even if @listofbooks.nil?
end
Aha, your revised post is better ... as noted in TL;DR: because Rails recreates controller objects on each request, you will need to persist anything you want next time around in your session or database.
The original post kind of fooled us by also clobbering @listofbooks
every time through the method, so we thought it was really a ruby question.