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

时间:2014-06-12 12:26:36

标签: ruby-on-rails metaprogramming redmine

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

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

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

1 个答案:

答案 0 :(得分:0)

尝试使用此代码

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