Mongoid update_attributes,复选框不删除未选中的值

时间:2013-12-16 19:26:50

标签: ruby-on-rails-3 has-and-belongs-to-many mongoid3

谷歌对此并不是很友好。

我有一个服务模型,它还保存了与类别模型的关系。

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_box?

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
非常感谢!

1 个答案:

答案 0 :(得分:0)

只需将此行放入update_attributes:

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