2013-12-16 63 views
0

谷歌對此不是很友好。Mongoid update_attributes複選框不刪除未經檢查的值

我有一個服務模型,它也保存了與類別模型的關係。

class Service 
    include Mongoid::Document 
    has_and_belongs_to_many :categories, inverse_of: :service 
end 

class Category 
    include Mongoid::Document 
    has_and_belongs_to_many :services, inverse_of: :category 
end 

服務/ _form.html.erb

<%= f.label "Category" %> 
<% @categories.each do |category| %> 
    <%= check_box_tag "service[category_ids][]", category.id, @service.category_ids.include?(category.id), id: dom_id(category) %> 
    <%= label_tag dom_id(category), category.name %><br> 
<% end %> 

有人能解釋如何刪除現有選中check_boxes?

class Pro::ServicesController < ApplicationController 

def update 
    @service = Service.find(params[:id]) 
    if params[:service][:category_ids] 
     params[:service] ||= {} 
     params[:service][:category_ids] ||= [] 
     # no clue how to delete existing relations 
     # params[:service][:category_ids] = ["1234567890","098765432"] 
    end 
    respond_to do |format| 
     if @service.update_attributes!(params[:service]) 
     format.html { redirect_to [:pro, @service], notice: 'Service was successfully updated.' } 
     format.json { head :no_content } 
     else 
     format.html { render action: "edit" } 
     format.json { render json: @service.errors, status: :unprocessable_entity } 
     end 
    end 
    end 
end 

非常感謝!

回答

0

簡單地把此行到您update_attributes方法:

@service.category_ids = params[:service][:category_ids]