I\'m trying to add an object to my array, however the array seems to always reset, instead of adding. What am I doing wrong? I think it has to do with if(defined? libr
since you're in a function libraryshelf
will never be defined as a local variable. And I'm guessing you are using Ruby 1.8.7 so then you are making a new array in a scope (that you shouldn't be able to see ) and assigning that to @listofbooks
I suggest
def add_book
@listofbooks ||= Array.new
@listofbooks.push(name)
@listofbooks # return the entire list, not the last thing pushed
end
This is a problem with the life cycle of the controller. For each request a new controller object is instantiated so any @variables are cleared between requests. You will need to store your variables by something like session[:booklist] = @booklist
, then retrieve it for the next request.