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| %>
<%= contact.name %>
<% end %>
<%= channel.name %>

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] = ContactChannel.new
@contacts_channels[i].contact_id = contact_id
@contacts_channels[i].channel_id = params[:channel_id][i]
@contacts_channels[i].save
end
end

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.

Advertisements

One thought on “Saving Arrays into Table

  1. kasim

    hello every one,
    if you know ,please help,
    i have followed this link (http://handyrailstips.com/tips/7-playing-mp3-s-on-your-rails-site-with-mp3_player) 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s