0

I am developing a small app in Rails 3. On one page I am gathering IDs for each user (in a each loop) in an array. Then I am putting the content of that array in a hidden text field and send it in to a method called "add_all". In this method I got a loop that is supposed to pick each users id and add it to the database one by one but it only adds the first one.

In the view (a bit simplyfied):

<% profileids = Array.new %>
<% @notfriends.each do |contact| %>
<% profileids << contact.id %>
<% end %>

<%= hidden_field_tag :profileids, profileids.join(",") %>

In the controller:

params[:profileids].each do |id|

@profile = Profile.find(params[:profile_id])

@contact = Contact.create(:profile_id => params[:profile_id], :friend_id => id)

@profile.contacts << @contact

end

Am I really doing this right? Why is the controller each not looping through the array?

2 Answers 2

2

You are calling "join" on your profileids array. This makes it a string and as such you cannot iterate through it using "each".

What you should do in your controller is this:

id_array = params[:profileids].split(",")
id_array.each do |id|
   @profile = Profile.find(params[:profile_id])
   @contact = Contact.create(:profile_id => params[:profile_id], :friend_id => id)
   @profile.contacts << @contact
end

Give that a shot and let us know how it works.

Sign up to request clarification or add additional context in comments.

Comments

0

try this

params[:profileids].split(",").each do |id|

Basically, you're attempting to iterate through a string and not an array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.