我想在 ruby on rails 中将字符串和数组数据放入 sqlite3
I want to put string and array data in sqlite3 in ruby on rails
嗨,我是编程新手,但我尝试制作自己的服务
我在 rails 和 sqlite3
上使用 cloud9 Ide、ruby
无论如何,我将解析字典的数据,并且我将要设计这样的数据库(仅作为示例)
[col-1] [col-2] [col-3]
[row-1] fruit apple [a,p,p,l,e]
[row-2] fruit kiwi [k,i,w,i]
...
[row-50] flower lily [l,i,l,y]
[row-51] flower rose [r,o,s,e]
...
3 列和数千行
为了提供更多详细信息,当用户在文本区域中键入 "fruit" 时,我想显示从 "apple" 到 "kiwi" 的单词列表!
我学会了存储 'string' 只有用户这样提交的
class CreateFans < ActiveRecord::Migration
def change
create_table :fans do |t|
t.string :username
t.timestamps null: false
end
end
end
但是我真的不知道如何存储自己的数据
我想知道如何添加列和行以及存储本地数据,而不是用户输入!
实际上,我昨天学习了阅读 .xlsx 文件并在 rails 到 gem 'roo' ruby 中显示,但我不知道如何正确使用它在数据库中。我想知道还有其他选择...
感谢您阅读我的问题,如果您能给我建议,我将不胜感激:)
您可以使用迁移向数据库添加列。
列不必只能来自用户输入。
例如,您可以进行迁移...
class CreateMyWord < ActiveRecord::Migration
def change
create_table :my_words do |t|
t.string :genre
t.string :word
t.string :letters
t.timestamps null: false
end
end
end
定义模型时指定属性 letters
实际上是一个数组...
class MyWord < ActiveRecord::Base
serialize :letters
end
serialize
会在存储记录时自动将数组转换为字符串表示形式,并在检索记录时自动将其转换回字符串表示形式。
然后您可以在 seeds.db
文件中自己填充 table,您可以使用命令 rake db:seed
执行该文件
种子数据库可能看起来像...
my_initial_words = [
['fruit', 'apple', ['a','p','p','l','e'],
['fruit', 'kiwi', ['k','i', 'w', 'i'],
...
]
my_iniital_words.each do |word_data|
MyWord.create(genre: word_data[0], word: word_data[1], letters: word_data[2])
end
请注意,如果单词 always 的字母与该单词匹配,那么您实际上并不需要数据库中的列 letters
,只需在在您需要时为您创建字母数组的模型。
class MyWord < ActiveRecord::Base
def letters
word.split('')
end
end
嗨,我是编程新手,但我尝试制作自己的服务
我在 rails 和 sqlite3
上使用 cloud9 Ide、ruby无论如何,我将解析字典的数据,并且我将要设计这样的数据库(仅作为示例)
[col-1] [col-2] [col-3]
[row-1] fruit apple [a,p,p,l,e]
[row-2] fruit kiwi [k,i,w,i]
...
[row-50] flower lily [l,i,l,y]
[row-51] flower rose [r,o,s,e]
...
3 列和数千行
为了提供更多详细信息,当用户在文本区域中键入 "fruit" 时,我想显示从 "apple" 到 "kiwi" 的单词列表!
我学会了存储 'string' 只有用户这样提交的
class CreateFans < ActiveRecord::Migration
def change
create_table :fans do |t|
t.string :username
t.timestamps null: false
end
end
end
但是我真的不知道如何存储自己的数据
我想知道如何添加列和行以及存储本地数据,而不是用户输入!
实际上,我昨天学习了阅读 .xlsx 文件并在 rails 到 gem 'roo' ruby 中显示,但我不知道如何正确使用它在数据库中。我想知道还有其他选择...
感谢您阅读我的问题,如果您能给我建议,我将不胜感激:)
您可以使用迁移向数据库添加列。
列不必只能来自用户输入。
例如,您可以进行迁移...
class CreateMyWord < ActiveRecord::Migration
def change
create_table :my_words do |t|
t.string :genre
t.string :word
t.string :letters
t.timestamps null: false
end
end
end
定义模型时指定属性 letters
实际上是一个数组...
class MyWord < ActiveRecord::Base
serialize :letters
end
serialize
会在存储记录时自动将数组转换为字符串表示形式,并在检索记录时自动将其转换回字符串表示形式。
然后您可以在 seeds.db
文件中自己填充 table,您可以使用命令 rake db:seed
种子数据库可能看起来像...
my_initial_words = [
['fruit', 'apple', ['a','p','p','l','e'],
['fruit', 'kiwi', ['k','i', 'w', 'i'],
...
]
my_iniital_words.each do |word_data|
MyWord.create(genre: word_data[0], word: word_data[1], letters: word_data[2])
end
请注意,如果单词 always 的字母与该单词匹配,那么您实际上并不需要数据库中的列 letters
,只需在在您需要时为您创建字母数组的模型。
class MyWord < ActiveRecord::Base
def letters
word.split('')
end
end