Dynamic Strong params for require - Rails

泄露秘密 提交于 2019-12-11 06:23:45

问题


I have an update method right now that will not work for all situations. It is hard coded in the strong params like this params.require(:integration_webhook).permit(:filters) that all fine right now but sometimes it may be integration_webhook and other times it needs to be integration_slack. Basically, is there a way that I don't need to hardcode the require in the strong params? I'll show my code for clarity.

Update Method:

    def update
     @integration = current_account.integrations.find(params[:id])

     attrs = params.require(:integration_webhook).permit(:filters)

     if @integration.update_attributes(attrs)
      flash[:success] = "Filters added"
      redirect_to account_integrations_path
     else
      render :filters
     end
   end

As you can see it's a standard update method. But I need the integration_webhook params to be dynamic. I'm wondering if there is a model method I could call to strip away the integration_webhook part?


回答1:


Not totally sure how dynamic this needs to be, but assuming that we are either getting an integratino_webhook or a integration_slack.

def update
  @integration = current_account.integrations.find(params[:id])

  if @integration.update_attributes(update_params)
    # ...
  else
    # ...
  end
end

private
  def update_params
    params.require(:integration_webhook).permit(:filters) if params.has_key?(:integration_webhook)
    params.require(:integration_slack).permit(:filters) if params.has_key?(:integration_slack)
  end

Checkout Strong parameters require multiple if this didn't answer your question.

Edit

For more dynamic requiring:

def update_params
  [:integration_webhook, :integration_slack].each do |model|
    return params.require(model).permit(:filters) if params.has_key?(model)
  end
end



回答2:


Off the top of my head something like this should work. The naming convention isn't the best but it the structure will allow you to just add to the list if you need to.

def update
     @integration = current_account.integrations.find(params[:id])

     if @integration.update_attributes(webhook_and_slack_params)
      flash[:success] = "Filters added"
      redirect_to account_integrations_path
     else
      render :filters
     end
   end


def webhook_and_slack_params
  [:integration_webhook, :integration_slack].each do |the_params|
  if(params.has_key?(the_params))
   params.require(the_params).permit(:filters)
  end
end


来源:https://stackoverflow.com/questions/39322195/dynamic-strong-params-for-require-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!