我的架构如下所示:
create_table "products", force: true do |t|
t.string "elements_list", default: [], array: true
end
我正在使用Rails 4并且目标是使用PostgreSQL的数组列类型,所以我没有在serialize :attribute, Class
中声明product.rb
。
@product
将保存,但这样做会丢弃序列化数组而不返回错误。为什么我会感到这种陌生感?我该如何解决?
[1] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.id
=> 1
[2] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.description
=> nil
[3] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.elements_list
=> []
[4] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.elements_list.class
=> Array
[5] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.id
=> 1
[6] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.description
=> nil
[7] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.elements_list
=> [1, 3]
[8] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.elements_list.class
=> Array
[9] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.update_attribute :description, "New description"
=> true
[10] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.save!
=> true
[11] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.description
=> "New description"
[12] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> Product.first.elements_list
=> []
[13] pry(#<RSpec::ExampleGroups::Product::AddToElementsList>)> @product.errors
=> #<ActiveModel::Errors:0x007f80e3348490
@base=
#<Product id: 1, name: "product-1", created_at: "2014-07-02 00:47:23", updated_at: "2014-07-02 00:48:31", description: "New description", latest_url: nil, resetting_cache: "f", for_sale: true, for_consulting: false, questions_list: [], elements_list: [1, 3], versioning: false>,
@messages={}>
更新
我已经通过从PostgreSQL&#39; S阵列列类型切换到Rail的序列化阵列来实现这一点,但除非基于PostgreSQL的解决方案(如果有的话),我还要留下这个问题有一个,帮助他人。
class Product < ActiveRecord::Base
serialize :elements_list, Array
end
class ChangeProductElementsListToText < ActiveRecord::Migration
def change
change_column :products, :elements_list, :text
change_column_default :products, :elements_list, nil
end
end