Saving Arrays into Table

Well, this must be common to all, as all of us has implemented this kind of feature somewhere in our projects.. But I found it challenging couple of times to implement this.. so I thought to share this small piece of code with you. Hope it helps someone..

Requirement: In this small project we are going to store multiple arrays into the database as each array will create a new row.

Let’s see how it works..

Here is my view(in your case it could be any)

<select name=”contacts_id[]” id=”contacts_id”>
<% current_user.contacts.all.each do |contact| %>
<%= %>
<% end %>
<%= %>

Now in this case we have two arrays one is for contact_id and another one is for channel_id, Let’s see how we will store those values into the table:

def create
@contacts_channels = []
params[:contact_id].each_with_index do |contact, i|
@contacts_channels[i] =
@contacts_channels[i].contact_id = contact_id
@contacts_channels[i].channel_id = params[:channel_id][i]

So what happens here? suppose you have an array of contact_id like this:
contact_id = [4,5,6]
and array of channel_id like this:
channel_id = [10, 11, 12]

So with the above script your values should go into the table like this
contact_id channel_id
4 10
5 11
6 12

What makes me puzzled here is, in case of relationship here like
Contact has_many :channels
how will this exact scenario works?

Please let me know your feedbacks, suggestions and queries. Your comment means lot to me.


One thought on “Saving Arrays into Table

  1. kasim July 13, 2010 / 6:33 AM

    hello every one,
    if you know ,please help,
    i have followed this link ( to integrate to mp3 player to my rails application

    i am trying to make autoplay and loop my player
    but my player working fine ,but no autostart and no loop
    my code
    true,:loop => true %>

    here “play_song”is helper which take current_user as argument ,this helper return location of song with paperclip plugin

    anyone help me

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s