我正在处理编辑项目的视图,其中包含一个包含所有项目字段的表单,而对于项目成员,我则会显示复选框。
当提交表单并且控制器接管时,我从param中删除了成员数组,以便我可以正确地更新项目。但是,我想知道是什么代码我应该使用成员更新表projects_users(现在在数组@members中)?
修改项目视图
<%= 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 %>
投影控制器:
...
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
...
表projects_users:
t.integer "project_id"
t.integer "user_id"
答案 0 :(得分:1)
使用Project的user_ids属性更新其用户:
# In the view:
<%= check_box_tag "project[user_ids][]", user.id, '1', :id => "user_#{user.id}" %>
# In the controller:
@project = Project.find(params[:id])
#@members = params[:project].delete(:members)
# you don't need this line since :
# params[:project][:members] became params[:project][:user_ids]
if @project.update_attributes(params[:project])
#...