I’m working on the view for editing a project, which contain of a form with all the project fields, and for the members of a project I render out checkboxes.
When the form is submitted and the controller takes over I remove the array of members from the param so I can update the project correctly. However, what I wonder is what code I should use to update the table projects_users with the members (now in the array @members)?
edit project view:
<%= form_for @project do |f| %>
...
the rest of the form
...
<div class="checkbox">
<% @members.each do |user| %>
<%= check_box_tag "project[members][]", user.id, '1', :id => "user_#{user.id}" %>
<%= label_tag "user_#{user.id}", user.first_name + ' ' + user.last_name, :class => "checkbox" %>
<% end %>
</div>
...
the rest of the form
...
<% end %>
projects controller:
...
def update
@project = Project.find(params[:id])
@members = params[:project].delete(:members)
if @project.update_attributes(params[:project])
... code for updating projects_users? ...
redirect_to users_projects_path
flash.now[:success] = 'Projektet redigerades.' # Not quite right!
else
render :action => "edit"
end
end
...
the table projects_users:
t.integer "project_id"
t.integer "user_id"
Use the user_ids attribute of Project to update its users: