[英]Rails Store Array in Database
I need to persist an array in my rails language learning app. 我需要在我的Rails语言学习应用程序中保留一个数组。 Here is the situation/reason I need to do this (if there is a better way please let me know).
这是我需要这样做的情况/原因(如果有更好的方法,请告诉我)。 The user is presented, one at a time, 10 words to learn.
一次向用户展示10个单词以供学习。 After the words are learned they get quized on the same set of 10 words.
单词被学习后,它们被量化为相同的10个单词集。
For the 'quiz' portion I would like to randomize the order the words appear in (for example: currently if you learn the words 1.fish 2.cat 3.dog... you will be quized in the same order 1.fish 2.cat 3.dog... which can make the quiz easier. 对于“测验”部分,我想将单词出现的顺序随机化(例如:当前,如果您学习单词1.fish 2.cat 3.dog ...,您将以相同的顺序被量化1.fish 2.cat 3.dog ...可以使测验更加容易。
I need to persist it in case the user were to log off or navigate away. 我需要坚持下去,以防用户注销或导航。 In this instance I want to return them to the exact word they left off on the quiz.
在这种情况下,我想将它们返回到他们在测验中遗漏的确切单词。
Here is the controller code I currently have: 这是我当前拥有的控制器代码:
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
The idea of the above is to pick a random number 0-9 and use it to reference a word in my DB. 上面的想法是选择一个随机数0-9,并用它来引用我的数据库中的单词。 The above results in something like the following in my DB for the random_exercise_array attribute:
上面的结果在我的数据库中为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"
Here is the relevant User DB code: 这是相关的用户数据库代码:
class DeviseCreateUsers < ActiveRecord::Migration
serialize :random_exercise_array
end
Relevant migration file: 相关迁移文件:
class AddRandomExerciseArrayToUsers < ActiveRecord::Migration
def change
add_column :users, :random_exercise_array, :text
end
end
Is this the best way to solve this problem? 这是解决这个问题的最好方法吗? If so, can you explain how to get back an integer from random_exercise_array without all of the (-)'s and (\\n')s?
如果是这样,您能否解释一下如何从random_exercise_array中取回没有所有(-)和(\\ n')的整数?
If you want get an array back from DB text column, you should declare the type in your user model like this: 如果要从数据库文本列取回数组,则应在用户模型中声明类型,如下所示:
class DeviseCreateUsers < ActiveRecord::Base #why your original code inherit from ActiveRecord::Migration?
serialize :random_exercise_array, Array
end
Then you can use current_user.random_exercise_array
as an array instead of a string. 然后,您可以使用
current_user.random_exercise_array
作为数组而不是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.