Ruby-on-rails 如何在rails中将数组保存到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23340222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to save array to database in rails
提问by tardjo
if i have params like this :
如果我有这样的参数:
params["scholarship"] = {"name"=>"test", "state_ids"=>["1", "2", "3", "4"]}
and when i create object to database field state_id not save to database?
当我创建对象到数据库字段 state_id 时没有保存到数据库?
how to save to database with format :
如何以格式保存到数据库:
#<Scholarship id: 1, name: "test", state_id: "["1", "2", "3", "4"]">
how do that?
怎么办?
thanks before
之前谢谢
采纳答案by Rubyist
For example:
例如:
class User < ActiveRecord::Base
serialize :scholarship
end
user = User.create(:scholarship=> { "name" => "test", "state_ids" => ["1", "2"]})
User.find(user.id).scholarship# => { "name" => "test", "state_ids" => ["1", "2"] }
回答by cnnr
Also you can use PostrgreSQL support for array storing. (If you're using PG of course). Your migration will look like that:
您也可以使用 PostrgreSQL 支持数组存储。(当然,如果您使用的是 PG)。您的迁移将如下所示:
add_column :table_name, :column_name, :string, array: true, default: []
But don't forget about validations.
但不要忘记验证。
回答by j-dexx
回答by TomDunning
state_ids != state_id
you've got 2 different names for your attribute, so they don't line up.
then use serialize :state_idsonce you've renamed the column.
您的属性有 2 个不同的名称,因此它们不会对齐。然后serialize :state_ids在重命名列后使用。
However if you're storing a list of state_ids, i'm going to guess you also have a states table, and so should look into using has_and_belongs_to_manyassociation.
但是,如果您要存储 state_id 列表,我猜您还有一个状态表,因此应该考虑使用has_and_belongs_to_many关联。

