Acts as array

acts_as_array makes possible to treat your array fields simply.

Build Status Coverage Status

Installation

Add the following to your Gemfile:

gem 'acts_as_array'

And then execute:

$ bundle

What is this for?

Say an user has multiple mail addresses. Typically you will define table schema as:

create_table :users do |t|
  t.string :name
end

create_table :mails do |t|
  t.string :address
  t.references :user
end

And, define ActiveRecord models as:

class Mail < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :mails
end

In this case, you will store multiple mail addresses to an users like:

ichiro = User.new(name: 'Ichiro')
ichiro.mails = [Mail.new(address: '[email protected]'), Mail.new(address: '[email protected]')]
ichiro.save

But, you want to set multiple mail addresses simply like followings?:

ichiro = User.new(name: 'Ichiro')
ichiro.mails = ['[email protected]', '[email protected]']
ichiro.save

Then, acts_as_array is available for you.

With acts_as_array

Use acts_as_array as:

class Mail < ActiveRecord::Base
  belongs_to :user
end

require 'acts_as_array'
class User < ActiveRecord::Base
  has_many :mails
  include ActsAsArray
  acts_as_array :mails => {:field => :address}
end

Then, it makes possible to set and get non-object array values like:

ichiro = User.new(name: 'Ichiro')
ichiro.mails = ['[email protected]', '[email protected]']
ichiro.save
User.first.mails #=> ['[email protected]', '[email protected]']

You can also get the original object array values with:

ichiro.obj_mails #=> [Mail.new(address: '[email protected]'), Mail.new(address: '[email protected]')]

Supported methods

Following ActiveRecord methods are supported to specify non-object array values:

  • create

create(field: non_object_array)

  • update_attributes

update_attributes(field: non_object_array)

  • update

update(field: non_object_array)

  • field=

{field} = non_object_array

Also, following getter methods are available:

  • field

Return non-object array values

  • obj_field

Return object array values

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request
  • Copyright (c) 2014 Naotoshi Seo. See LICENSE for details.