A Brief Introduction to Ruby on Rails's support for PostgreSQL array types, railspostgresql

Source: Internet
Author: User

A Brief Introduction to Ruby on Rails's support for PostgreSQL array types, railspostgresql

I am very happy to announce that Rails 4.0 now supports PostgreSQL array types. you can easily create fields of the array type through: array => true in migration. you can also add other options (length, default, and so on) when creating an array field)
 

create_table :table_with_arrays do |t|
 t.integer :int_array, :array => true
 # integer[]
 t.integer :int_array, :array => true, :length => 2
 # smallint[]
 t.string :string_array, :array => true, :length => 30
 # char varying(30)[]
end

Note that when setting the default value for fields of the array type, you should write ({value, another value}) in Postgresql }), if you want to set the default value of an array field to an empty array, you should use: default => '{}'
 

create_table :table_with_arrays do |t|
 t.integer :int_array, :array => true, :default => '{}'
 # integer[], default == []
 t.integer :int_array, :array => true, :length => 2, :default => '{1}'
 # smallint[], default == [1]
end


Example of using Postgresql array in Model

We now have a user model that contains first_name, last_name, And nickname. The nickname field is of the array type. The following migration Code creates a table:
 

create_table :users do |t|
 t.string :first_name
 t.string :last_name
 t.string :nicknames, :array => true
end

We have a simple model for this table.
 

class User < ActiveRecord::Base
 attr_accessible :first_name, :last_name, :nicknames
end

We do not use the default value for the field. If we use a User object for an instance, the code is like this.
 

john = User.create(:first_name => 'John', :last_name => 'Doe')

If john. nickname is called, nil is returned and NULL value is stored in postgreSQL.

The following code sets the value of the nickname attribute during creation.
 

john = User.create(:first_name => 'John', :last_name => 'Doe', :nicknames => ['Jack', 'Johnny'])

If we get records from the database, the nick_name field will be converted into an array instead of returning the string {Jack, Johnny }!. Rails 4.0 has a pure Ruby array converter, but if you want to accelerate the conversion process, you can use the previously mentioned pg_array_parser gem. PgArrayParser has a C-based extension and a Java Implementation of JRuby (even if this gem has some problems in JRuby, I am trying to solve this problem .)

Note that when interacting with an array (or other variable values) in a model. ActiveRecord does not currently track "destructive", or change where it occurs. This includes the push and pop operations of arrays. If you need to use "destructive" for update, you must use call <attribute> _ will_change! This allows ActiveRecord to know the value of the attribute you need to change. For our User model, if you want to append an element after nickname, you can do this:
 

john = User.first
 
john.nicknames + = ['Jackie boy']
# Or
john.nicknames = john.nicknames.push ('Jackie boy')
# At any time, the attribute is assigned by "=", ActiveRecord will track this change
john.save
 
john.reload
john.nicknames
# => ['Jack', 'Johnny', 'Jackie Boy']
 
john.nicknames.pop
john.nicknames_will_change!
# '#pop' operation changes the value of the array, so we need to tell ActiveRecord that it will change
john.save

 

The last thing to note when using arrays in Postgresql is that there is no limit on the number of elements in an array. It can be a multi-dimensional array. However, when using multi-dimensional arrays, the number of sub-array elements must be the same.

 

[[1,2,3], [2,3,4], [4,5, nil]]
# Available in PostgreSQL, the number of elements in each subarray is the same
 
[1,2, [3,4]]
# Unavailable array 



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.