Adding A Column Type Array To Mysql Database Table In Rails
TAGS:
Rails Array Column Mysql
How To Add A Column Type Array To Mysql Database Table
In our example, We suppose that you watched our tutorial about rails application with mysql database.
Creating Migration
First, We need to create a migration file to do our mission, Creating a column named reader type text as:
rails g migration AddReaderToPosts reader:string
This will create a migration file like:
class AddReaderToPosts < ActiveRecord::Migration
def change
add_column :posts, :reader, :string
end
end
Edit app/models/post.rb
to be like:
class Post < ActiveRecord::Base
serialize :reader, Array
end
Then make migrate as:
rake db:migrate
Now, You have a reader
column which is an array, it can take many values as any array[`up to tons of tons …].
And you can access the arry values in rails console as follow:
a=Post.first
# push "Mamdouh"
a.reader << "Mamdouh"
# push "Ali"
a.reader << "Ali"
# push "Soso"
a.reader << "Soso"
# puts reader array values
a.reader
# traverse the reader array
a.reader.each do |x|
puts x
end
# get count
a.reader.count
# clear all values
a.reader.clear
Now, Take a look to this tutorial video.