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.

Advertisement