Problems keeping an object in an array, Ruby issues and Rails issues

前端 未结 3 1918
甜味超标
甜味超标 2021-01-03 20:17

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

3条回答
  •  [愿得一人]
    2021-01-03 21:12

    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
    

    Edit to reflect updated question

    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.

提交回复
热议问题