如果我的参数像这样:
params["scholarship"] = {"name"=>"test", "state_ids"=>["1", "2", "3", "4"]}
当我创建对象并将state_id字段保存到数据库时,为什么它没有被保存到数据库中?如何按以下格式保存到数据库:
#<Scholarship id: 1, name: "test", state_id: "["1", "2", "3", "4"]">
怎么做到这一点?
先行致谢。
如果我的参数像这样:
params["scholarship"] = {"name"=>"test", "state_ids"=>["1", "2", "3", "4"]}
当我创建对象并将state_id字段保存到数据库时,为什么它没有被保存到数据库中?#<Scholarship id: 1, name: "test", state_id: "["1", "2", "3", "4"]">
怎么做到这一点?
先行致谢。
另外,如果您使用的是PG数据库,您可以使用PostrgreSQL支持的数组存储功能。您的迁移将如下所示:
your_migration.rb
def up
enable_extension 'pgcrypto'
add_column :table_name, :column_name, :integer, array: true, default: []
end
def down
remove_column :table_name, :column_name
end
add_column :table_name, :column_name, :string, array: true, default: []
但不要忘记验证。
例如:
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"] }
state_ids != state_id
你的属性有两个不同的名称,所以它们不匹配。
在重命名列之后,使用serialize :state_ids
。
然而,如果你正在存储一个状态 ID 列表,我猜你也有一个 states 表,因此应该考虑使用 has_and_belongs_to_many 关联。
state_ids
- Stefan