取消选择Rails复选框中的空值



在我的应用程序中,如果用户必须取消选中他通知的所有复选框,则保存为null Array []

我在启动Action UPDATE后使用params[: parameter1] [: parametro2_ids] | | = [],但是如果我试图清除日志中返回的所有轨道:

NoMethodError (undefined method '[]' for nil: NilClass):。在正常逻辑中,它应该是功能性的。我怎么能实现一个函数,如果它没有被检查或未被检查,都是毫无价值的?

responsabilities_controller

class ResponsabilitiesController < ApplicationController
  def index
    @responsabilities = Responsability.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @responsabilities }
    end
  end
  def show
    @responsability = Responsability.find(params[:id])
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @responsability }
    end
  end

  def new
    @responsability = Responsability.new
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @responsability }
    end
  end

  def edit
    @responsability = Responsability.find(params[:id])
  end

  def create
    @responsability = Responsability.new(params[:responsability])
    respond_to do |format|
      if @responsability.save
        format.html {
          flash[:notice] = l(:notice_success)
          redirect_to :contoller => "uc_rh",:action => "index"
        }
      else
        format.html { render action: "new" }
        format.json { render json: @responsability.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
      params[:responsability][:knowledge_ids] || [] if params[:responsability].present?
      params[:responsability][:competence_ids] || [] if params[:responsability].present?
      params[:responsability][:tool_ids] || [] if params[:responsability].present?
    @responsability = Responsability.find(params[:id])
    respond_to do |format|
      if @responsability.update_attributes(params[:responsability])
        format.html {
          flash[:notice] = l(:notice_success_edit)
          redirect_to :contoller => "responsabilities",:action => "edit"
        }
      else
        format.html { render action: "edit" }
        format.json { render json: @responsability.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @responsability = Responsability.find(params[:id])
    @responsability.destroy
    respond_to do |format|
      format.html { redirect_to responsabilities_url }
      format.json { head :no_content }
    end
  end

  def nested_knowledges
    @responsability = Responsability.find(params[:id])
  end

  def nested_competences
    @responsability = Responsability.find(params[:id])
  end

  def nested_tools
    @responsability = Responsability.find(params[:id])
  end

end

尝试使用此代码

params[:parameter1][:parametro2_ids] ||= [] if params[:parameter1].present?

最新更新