在ruby中为每个用户创建一个全局数组 [英] Make a global array for each user in ruby

查看:140
本文介绍了在ruby中为每个用户创建一个全局数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我正试图找出最好/最简单的方法来解决这个问题。



我的应用有多个用户。该应用程序允许用户将书籍添加到读取队列列表中(如用户可以查看的书籍列表)。



最初,我设置了读取队列列表为全局数组。但是这意味着多个用户将书籍添加到单个全局数组中。如果user1添加了3本书,user2也会看到这3本书。或者,如果user1清除了读取队列列表,user2的书籍也被清除了。



可能的解决方案:


  1. 也许我可以在数组中创建一个键来将它的一部分与用户相关联,但是我想这个数组会变得非常大......


  2. 也许创建一个数据库表queue-list..但这看起来像是很多事情要做这样的事情。


  3. 也许为每个用户创建一个唯一的全局数组。 (我喜欢这个,但不知道该怎么做)


希望这很清楚,



我在解决方案3中的尝试:

books_controller .rb

  def add_book_to_queue 
user = User.find(params [:id])
user。 read_queuelist.push(params [:book_info])
@readlist = user.read_queuelist
end






user.rb

  def read_queuelist 
$ read_queuelist || = Array.new
end






view

 <%= @readlist%> 





解决方案

由于您是Rails的新手,我想您会发现使用ActiveRecord将模型数据保存到数据库最终会成为最简单的解决方案。


I have an issue and I'm trying to figure out the best/simplest way to resolve this...

I have multiple users on my app. the app allows users to add books to a read-queue list (like a list of books a user can keep tabs on).

Originally, I set the read-queue list as a global array. However this meant that multiple users were adding books to a single global array. If user1 added 3 books, user2 would also see those 3 books. Or if user1 cleared the read-queue list, user2's books were cleared too.

Possible Solutions:

  1. Maybe I can create a key in the array to associate a portion of it to a user, but I imagine that the array would get pretty large...

  2. Maybe create a db table "queue-list".. but that seems like a lot to do for something like this..

  3. Maybe create a global array unique for each user. (I like this one, but not sure how to do that)

Hope this is clear, I'm pretty new to rails so any help is appreciated!

my attempt at solution 3:

books_controller.rb

def add_book_to_queue
  user = User.find(params[:id])
  user.read_queuelist.push(params[:book_info])
  @readlist = user.read_queuelist
end


user.rb

def read_queuelist
  $read_queuelist ||= Array.new
end


view

<%= @readlist %> 


解决方案

Since you're new to Rails, I think you'll find that using ActiveRecord to persist your model data to a database ends up being the simplest solution.

这篇关于在ruby中为每个用户创建一个全局数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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