Make a global array for each user in ruby

和自甴很熟 提交于 2019-12-13 04:58:17

问题


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


回答1:


If your app is simple enough, you could make an array for each user as it's shown below. But if your application is meant to handle a lot of users and tons of books, you should look towards DB integration.

class Book
  attrr_accessor :title, :author

  def initialize(t, a)
    @title, @author = t, a
  end
end

class User
  attr_accessor :books

  def initialize
    @books =  Array.new
  end

  def add(b)
    @books << b
  end
end

joe = User.new

joe.add(Book.new("moo", "foo"))

puts "Joe likes #{joe.books.length} books"

UPD: for rails, take a look at has_many and belongs_to associations.




回答2:


You can create lots of global hashes with Redis. It has the advantage of scaling and being optionally persistant (via backups). See http://redis.io/commands#hash and http://redistogo.com/ for free Redis hosting.




回答3:


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.



来源:https://stackoverflow.com/questions/4839409/make-a-global-array-for-each-user-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!