2013-02-11 88 views
0

我工作的視圖編輯項目,其中包含一個表單的所有項目領域,併爲項目的成員我呈現出複選框。更新關係表

當表單提交,並且控制器接管我從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" 
+1

使用'項目user_ids'屬性:你check_box_tag重命名爲'check_box_tag 「項目[user_ids] []」 #...'然後讓這在params散列(不做'params [:project] .delete(:user_ids)',讓它在params中) – MrYoshiji 2013-02-11 22:26:54

+0

再次感謝!您應該將您的評論轉換爲答案,以便我可以接受它:) – holyredbeard 2013-02-11 22:33:07

+0

我剛剛發佈爲答案,今天感謝您的聲譽! Ahah – MrYoshiji 2013-02-11 22:36:04

回答

1

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