ruby on rails-更新关系表



我正在编辑一个项目的视图,该视图包含一个包含所有项目字段的表单,对于项目的成员,我呈现出复选框。

当表单提交并由控制器接管时,我会从参数中删除成员数组,以便正确更新项目。然而,我想知道的是,我应该使用什么代码来更新具有成员的表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"

使用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])
  #...

相关内容

  • 没有找到相关文章

最新更新