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

前端 未结 3 1922
甜味超标
甜味超标 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:07

    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.

提交回复
热议问题