繁体   English   中英

数据库中的Rails存储阵列

[英]Rails Store Array in Database

我需要在我的Rails语言学习应用程序中保留一个数组。 这是我需要这样做的情况/原因(如果有更好的方法,请告诉我)。 一次向用户展示10个单词以供学习。 单词被学习后,它们被量化为相同的10个单词集。

对于“测验”部分,我想将单词出现的顺序随机化(例如:当前,如果您学习单词1.fish 2.cat 3.dog ...,您将以相同的顺序被量化1.fish 2.cat 3.dog ...可以使测验更加容易。

我需要坚持下去,以防用户注销或导航。 在这种情况下,我想将它们返回到他们在测验中遗漏的确切单词。

这是我当前拥有的控制器代码:

def index 
  .
  .
  @quiz = Lang.limit(10).offset(current_user.bookmark - 11)  
  exercise_bank
  .
  .    
end

private
  def exercise_bank
    current_user.random_exercise_array = (0..9).step(1).shuffle
    current_user.save
    @index2 = current_user.random_exercise_array[@index] 
    #@index starts at 0 and increments on each call to index action
    #@index2 grabs the random number and uses it to reference a word in @quiz
    #something like this: @quiz[@index2].spanish_to_english---grabs a english word
  end
end

上面的想法是选择一个随机数0-9,并用它来引用我的数据库中的单词。 上面的结果在我的数据库中为random_exercise_array属性生成了以下内容:

random_exercise_array: "---\n- 6\n- 0\n- 1\n- 7\n- 8\n- 5\n- 9\n- 3\n- 2\n- 4\n"

这是相关的用户数据库代码:

class DeviseCreateUsers < ActiveRecord::Migration
  serialize :random_exercise_array
end

相关迁移文件:

class AddRandomExerciseArrayToUsers < ActiveRecord::Migration
  def change
    add_column :users, :random_exercise_array, :text
  end
end

这是解决这个问题的最好方法吗? 如果是这样,您能否解释一下如何从random_exercise_array中取回没有所有(-)和(\\ n')的整数?

如果要从数据库文本列取回数组,则应在用户模型中声明类型,如下所示:

class DeviseCreateUsers < ActiveRecord::Base  #why your original code inherit from ActiveRecord::Migration?
  serialize :random_exercise_array, Array
end

然后,您可以使用current_user.random_exercise_array作为数组而不是字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM