Habtm checkboxes


#1

I have a form with a table in it where every cell has a checkbox.

Name |comany_1 company_2 company_n

index_1|
index_2|
index_n|

On submitting the form, a hash like so

“index”=>{“11”=>{“company_ids”=>[“9”]}, “12”=>{“company_ids”=>[“9”]},
“13”=>{“company_ids”=>[“9”]}, “10”=>{“company_ids”=>[“9”]}}}

is sent to my sendconfirm action:

def sendconfirm
@project = Project.find(params[:project])
@indices = Index.find(:all)
@sender_u = @session[:user]
@sender_c = @sender_u.company
if params[:index]
params[:index].each do |index, value |
@index = Index.find(index)
@index.update_attributes(value)

@index.push_with_attributes(value, :current_user =>

@session[:user][:id]))
end
flash[:notice] = “Update Successful”
redirect_to :action => ‘index’, :project => @project
else
flash[:notice] = “You didn’t tick any boxes”
redirect_to :action => ‘sendout’, :project => @project
end
end

This all works fine. My join table has an extra attribute for catching
the
id of the user currently logged on. I thought I could use
push_with_attributes as im the comment above but it won’t work in this
situation.

Any ideas how I can add the attributes for current_user to my join table
while params[:index] is being iterated through?

Thanks in advance

Adam


#2

push_with_attributes is a collection method

from the looks of it, each iteration through params[:index] yields:

i = 11, v = { company_ids => [9] }
i = 12, v = { company_ids => [9] }
etc…

so i think what you need to do is

def sendconfirm

params[:index].each do |i, v|
# find the index
index = Index.find(i)

# get companies that were submitted for this index
companies = Company.find(v[:company_ids]) # v[:company_ids] is an 

array

# for each company submitted, add it to the collection
companies.each do |c|
  index.companies.push_with_attributes(c, :current_user =>

@sesion[:user][:id])
end

end
end

hope this helps.

Chris