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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:34:42  来源:igfitidea点击:

how to save array to database in rails

ruby-on-railsarraysparams

提问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

ActiveRecord::Base.serialize.

ActiveRecord::Base.serialize

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

In your model have

在你的模型中有

serialize :state_ids

Here is a linkto the documentation

这是文档的链接

That being said it looks like you're trying to pass state_ids parameters and save it in state_id, is this what you're intending to do?

话虽如此,您似乎正在尝试传递 state_ids 参数并将其保存在 state_id 中,这是您打算做的吗?

回答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关联。