问题保持一个对象的数组,Ruby的问题和Rails问题 [英] Problems keeping an object in an array, Ruby issues and Rails issues

查看:78
本文介绍了问题保持一个对象的数组,Ruby的问题和Rails问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将对象添加到我的阵列,但是阵列似乎永远重,而不是增加。我究竟做错了什么?我认为这与做的,如果(定义?libraryshelf),那么,我想在这里做的是找出数组存在与否(如果这是先加或不)。

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? libraryshelf) then, What I'm trying to do here is find out of the array exists or not (if this is the first add or not)..

def add_book
  @listofbooks ||= Array.new
  @listofbooks.push(params[:booktitle])
  @listofbooks
  respond_to do |format|
    format.html { redirect_to(:back) }
    format.js
  end
end

我add_book.js.erb文件

my add_book.js.erb file

alert('<%= @listofbooks %>');

@listofbooks 只显示我的书最后添加的标题。

@listofbooks only shows the title of the book I last added..

推荐答案

TL; DR:的控制器的是无状态的,他们只是看到传入的请求。为了有一个列表活得比当前请求,你需要坚持无论是在会议上或在数据库中的表,这取决于你想要多久的生活和其他方面的考虑。

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...

不要使用定义?对,其实,不要定义?任何东西使用。它不具有许多合法的应用程序级的用途。在这种情况下, libraryshelf 是一个局部变量,以及在该方法中其第一参考它将永远不能被定义

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.

直接在 @listofbooks 操作,只是检查 @listofbooks或@ listofbooks.nil?

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

啊哈,你修改后比较好...在TL指出,DR:由于Rails对每个请求重新创建控制器对象,你需要坚持什么,你想下一次在你的会话或数据库各地

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.

原帖那种通过的也愚弄了我们的重挫 @listofbooks 通过方法每一次,所以我们认为这是一个真正的红宝石问题

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.

这篇关于问题保持一个对象的数组,Ruby的问题和Rails问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆