Search code examples
ruby-on-railsjsonstrong-parameterswhitelist

White listing JSON parameters using Strong Parameters in rails


I have this ajax call which sends a JSON -

$.ajax({
        data: JSON_main_data,
        url: '/daily_work_updates',
        type: "POST",

        success: function(data){
            if (data ==true)
            alert("Data saved successfully");

            else
            alert("Data not saved successfully");
        },
        dataType: 'JSON',
        contentType : 'application/json'
      });

When I try to save this to a database it needs to be whitelisted using strong parameters for rails 4.

This is the call to the StrongParamter function-

DailyWorkUpdate.new(daily_work_update_params)

The strongparameter method-

private
  def daily_work_update_params 
  params.require(:save_daily).permit(:attr1)
  end

This throws an error in the browser which says- undefined method `permit' for #ARRAY

This is the JSON sent to the controller-

{"save_daily"=>[{"attr1"=>"AGNE_WI_UCMS"}]}

I have been stuck here for long now. Any help would be appreciated.


Solution

  • So there seem to be a lot of problems whitelisting JSON parameters. To my understanding this is something which needs to be reported to the rails developers. Anyway, I have a work around solution for the same WITHOUT whitelisting the parameters (which is bad coding standard but the only solution I found).

    My controller -

         def create
                (0..params[:length].to_i - 1).each do |i|
                  @saved = false
                  @saved=DailyWorkUpdate.WriteRecordDailyWorkUpdate(params[:save_daily][i])
                end 
        end
    

    So I directly inserted the values using a SQL query in my model-

    def self.WriteRecordDailyWorkUpdate(save_daily)
        @connection = ActiveRecord::Base.establish_connection
        DailyWorkUpdate.connection.execute("INSERT INTO `daily_work_update`(`DATE`) 
                                                                    VALUES ('"+save_daily["DATE"]')
    
        return true
      end
    

    Please feel free to improve this answer. It would help me too. But for now, This is trhe best work around for those who are stuck with this problem.