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.

One response to “Saving Arrays into Table”

  1. kasim Avatar
    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 to kasim Cancel reply

I’m Puneet

Namaste! I’m Puneet, and this is my digital space for all things tech. I dive deep into topics like backend engineering, software architecture, and how we build robust systems. I believe in writing simple, practical articles that you can learn from and apply. Let’s build something great together!